© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 10 - 1 Chapter 10 Sorting and Searching.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 11 Sorting and Searching.
Advertisements

Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
CSE Lecture 3 – Algorithms I
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Chapter 19: Searching and Sorting Algorithms
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Chapter 11 Sorting and Searching. Topics Searching –Linear –Binary Sorting –Selection Sort –Bubble Sort.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
C++ Plus Data Structures
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 8 ARRAYS Continued
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
UNIT 18 Searching and Sorting.
Applications of Arrays (Searching and Sorting) and Strings
Chapter 19: Searching and Sorting Algorithms
Lecture 12. Searching Algorithms and its analysis 1.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Array (continue).
CS1101: Programming Methodology Aaron Tan.
CSC 211 Data Structures Lecture 13
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Data Structure Introduction.
Comparison-Based Sorting & Analysis Smt Genap
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting.
CS1101: Programming Methodology
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Sorting and Searching. Searching  Problem definition: Given a value X, return the index of X in the array if such X exist. Otherwise, return NOT_FOUND(-1).
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Searching and Sorting Searching algorithms with simple arrays
Searching and Sorting Arrays
Chapter 9: Sorting and Searching Arrays
Introduction to Search Algorithms
Describing algorithms in pseudo code
Searching and Sorting Arrays
Searching and Sorting Arrays
Module 8 – Searching & Sorting Algorithms
Chapter 11 Sorting and Searching
Presentation transcript:

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Sorting and Searching

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Objectives After you have read and studied this chapter, you should be able to Perform linear and binary search algorithms on small arrays. Determine whether a linear or binary search is more effective for a given situation. Perform selection and bubble sort algorithms. Describe the heapsort algorithm and show how its performance is superior to the other two algorithms. Apply basic sorting algorithms to sort an array of objects.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Searching When we maintain a collection of data, one of the operations we need is a search routine to locate desired data quickly. We will use an array of integers to present searching algorithms. Here’s the problem statement: Given a value X, return the index of X in the array, if such X exists. Otherwise, return NOT_FOUND (-1). We assume there are no duplicate entries in the array. We will count the number of comparisons the algorithms make to analyze their performance. The ideal searching algorithm will make the least possible number of comparisons to locate the desired data. Two separate performance analyses are normally done, one for successful search and another for unsuccessful search.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Search Result number Unsuccessful Search: Successful Search: NOT_FOUND search( 45 ) search( 12 ) 4

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Linear Search Search the array from the first to the last position in linear progression. public int linearSearch ( int[] number, int searchValue ) { int loc = 0; while ( loc < number.length && number[loc] != searchValue ) { loc++; } if ( loc == number.length) { //Not found return NOT_FOUND; } else { return loc; //Found, return the position }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Linear Search Performance We analyze the successful and unsuccessful searches separately. We count how many times the search value is compared against the array elements. Successful Search Best Case – 1 comparison Worst Case – N comparisons (N – array size) Unsuccessful Search Best Case = Worst Case – N comparisons

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Binary Search If the array is sorted, then we can apply the binary search technique. number The basic idea is straightforward. First search the value in the middle position. If X is less than this value, then search the middle of the left half next. If X is greater than this value, then search the middle of the right half next. Continue in this manner.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Successful Search search( 44 ) lowhighmid 0808 #1 high low 38 < 44 low = mid+1 = 5 mid 4

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Successful Search search( 44 ) lowhighmid 0808 #1 44 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Successful Search search( 44 ) lowhighmid 0808 #1 44 == #2 6 highlow5 #3 mid 5 Successful Search!!

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 #1 high low 38 < 45 low = mid+1 = 5 mid 4

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 #1 45 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 #1 44 < #2 6 highlow5 #3 mid 5 low = mid+1 = 6

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 # #2 65 #3 5 highlow 6565 #4 Unsuccessful Search low > high no more elements to search

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Binary Search Routine public int binarySearch ( int[] number, int searchValue ) { int low = 0, high = number.length - 1, mid= (low + high) / 2; while ( low <= high && number[mid] != searchValue ) { if (number[mid] < searchValue) { low = mid + 1; } else { //number[mid] > searchValue high = mid - 1; } mid = (low + high) / 2; //integer division will truncate } if ( low > high) { mid = NOT_FOUND; } return mid; }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Binary Search Performance Successful Search Best Case – 1 comparison Worst Case – log 2 N comparisons Unsuccessful Search Best Case = Worst Case – log 2 N comparisons Since the portion of an array to search is cut into half after every comparison, we compute how many times the array can be divided into halves. After K comparisons, there will be N/2 K elements in the list. We solve for K when N/2 K = 1, deriving K = log 2 N.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Comparing N and log 2 N Performance Array SizeLinear – NBinary – log 2 N

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sorting When we maintain a collection of data, many applications call for rearranging the data in certain order, e.g. arranging Person information in ascending order of age. We will use an array of integers to present sorting algorithms. Here’s the problem statement: Given an array of N integer values, arrange the values into ascending order. We will count the number of comparisons the algorithms make to analyze their performance. The ideal sorting algorithm will make the least possible number of comparisons to arrange data in a designated order. We will compare different sorting algorithms by analyzing their worst-case performance.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Selection Sort 1. Find the smallest element in the list min first exchange sorted unsorted This is the result of one pass. 2. Exchange the element in the first position and the smallest element. Now the smallest element is in the first position. 3. Repeat Step 1 and 2 with the list having one less element (i.e., the smallest element is discarded from further processing).

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Selection Sort Passes sorted Pass # Result AFTER one pass is completed.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Selection Sort Routine public void selectionSort( int[] number ) { int startIndex, minIndex, length, temp; length = number.length; for (startIndex = 0; startIndex <= length-2; startIndex++){ //each iteration of the for loop is one pass minIndex = startIndex; //find the smallest in this pass at position minIndex for (i = startIndex+1; i <= length-1; i++) { if (number[i] < number[minIndex]) minIndex = i; } //exchange number[startIndex] and number[minIndex] temp = number[startIndex]; number[startIndex] = number[minIndex]; number[minIndex] = temp; }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Selection Sort Performance We derive the total number of comparisons by counting the number of times the inner loop is executed. For each execution of the outer loop, the inner loop is executed length – start times. The variable length is the size of the array. Replacing length with N, the array size, the sum is derived as…

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Bubble Sort With the selection sort, we make one exchange at the end of one pass. The bubble sort improves the performance by making more than one exchange during its pass. By making multiple exchanges, we will be able to move more elements toward their correct positions using the same number of comparisons as the selection sort makes. The key idea of the bubble sort is to make pairwise comparisons and exchange the positions of the pair if they are out of order.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter One Pass of Bubble Sort The largest value 90 is at the end of the list exchange ok exchange

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Bubble Sort Routine public void bubbleSort( int[] number ) { int temp, bottom, i; boolean exchanged = true; bottom = number.length - 2; while ( exchanged ) { exchanged = false; for (i = 0; i <= bottom; i++) { if (number[i] > number[i+1]) { temp = number[i]; //exchange number[i] = number[i+1]; number[i+1] = temp; exchanged = true; //exchange is made } bottom--; }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Bubble Sort Performance In the worst case, the outer while loop is executed N-1 times for carrying out N-1 passes. For each execution of the outer loop, the inner loop is executed bottom+1 times. The number of comparisons in each successive pass is N-1, N-2, …, 1. Summing these will result in the total number of comparisons. So the performances of the bubble sort and the selection sort are approximately equivalent. However, on the average, the bubble sort performs much better than the selection sort because it can finish the sorting without doing all N-1 passes.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sorting and Searching in Java Java provides a rich set of utilities, defined in the classes Arrays, for sorting and searching data. static void sort(int[] a) – Sorts the specified array of ints into ascending numerical order. static int binarySearch(int[] a, int key) – Searches the specified array of ints for the specified value using the binary search algorithm. Similar methods for other data types byte, short, char, float and double are also provided. [e.g. binarySearch(float[] a, float key) ] You even can sort and search any kinds of objects by using Arrays.sort() and Arrays.search().

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sorting in Java - Example import java.util.Arrays; class AP10_1 { public static void main(String s[]) { int data[] = {12, 91, 15, 21, 6, 17, 28, 30, 55, 10}; int N = data.length; int i; System.out.print("Data items in original order\n"); for (i = 0; i <= N - 1; i++) System.out.print(data[i]+ " " ); Arrays.sort(data); System.out.print("\nData items in ascending order\n"); for (i = 0; i <= N - 1; i++) System.out.print(data[i]+ " " ); System.out.println(); } Data items in original order Data items in ascending order

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Searching in Java public static int binarySearch(float[] a, float key) Searches the specified array of floats for the specified value using the binary search algorithm. The array must be sorted (as by the sort method, above) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found. Parameters: a - the array to be searched. key - the value to be searched for. Returns: index of the search key, if it is contained in the list; otherwise, (- (insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Searching in Java - Example import java.util.Arrays; class AP10_2 { public static void main(String s[]) { int data[] = {6, 10, 12, 15, 17, 21, 28, 30, 55, 91 }; System.out.print("Searching 12 result : "); System.out.println(Arrays.binarySearch(data, 12)); System.out.print("Searching 30 result : "); System.out.println(Arrays.binarySearch(data, 30)); System.out.print("Searching 91 result : "); System.out.println(Arrays.binarySearch(data, 91)); System.out.print("Searching 8 result : "); System.out.println(Arrays.binarySearch(data, 8)); System.out.print("Searching 123 result : "); System.out.println(Arrays.binarySearch(data, 123)); } Searching 12 result : 2 Searching 30 result : 7 Searching 91 result : 9 Searching 8 result : -2 Searching 123 result : -11

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Sorting Objects in Java Problem Statement A dd the sorting capability to the AddressBook class from Chapter 9. The new AddressBook class will include a method that sort Person objects in alphabetical order or in descending order of their ages. How do we compare Person objects? The following is invalid: Person p1 = …; Person p2 = …; if ( p1 < p2 ) { … }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Comparable The sort method needs to know how to compare the objects defined by you so that it can determine the ordering of your objects. You can let Arrays.sort() to do so by implementing the interface comparable in your class. The interface Comparable has one method compareTo needed to define. public int compareTo(Object o) - Compares this object with the specified object o for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.Object

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Comparable - Example class Person implements Comparable{ String name; int age; public Person(String n, int a) { name = n; age = a; } public String getName() { return name;} public int getAge() { return age;} public int compareTo(Object o) { Person p = (Person) o; return name.compareTo(p.name); // use String.compareTo }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter import java.util.Arrays; class AP10_3 { public static void main(String s[]) { Person data[] = new Person[5]; data[0] = new Person("LAU Tak Wah, Andy", 43); data[1] = new Person("LAI Ming, Leon", 33); data[2] = new Person("Cheung Hok Yau, Jacky", 50); data[3] = new Person("KWOK Fu Shing, Arron", 26); data[4] = new Person("CHAN Tai Man, Johnny", 44); int N = data.length; int i; Arrays.sort(data); System.out.print("Data items in ascending order:\n"); for (i = 0; i <= N - 1; i++) System.out.println(data[i].getName()+" "+data[i].getAge()); } Comparable – The main method Data items in ascending order: CHAN Tai Man, Johnny 44 Cheung Hok Yau, Jacky 50 KWOK Fu Shing, Arron 26 LAI Ming, Leon 33 LAU Tak Wah, Andy 43

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Comparator What happens if we want to sort the Person objects by age? You have to modify the CompareTo method to compare the ages rather than the names. Implementing Comparable can only let you sort your data by one attribute. i.e. You cannot sort by names any more. You can use another interface called Comparator to perform sorting on more than one attributes. For each attribute you want to perform the sorting, you need to write one class to implement the interface Comparator which has two methods to be defined by the programmer: int compare(Object o1, Object o2) Compares its two arguments for order. boolean equals(Object obj) Indicates whether some other object is "equal to" this Comparator.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Comparator - Example // class Person same as before import java.util.Comparator; class ByAgeComparator implements Comparator { public int compare(Object o1, Object o2) { Person p1 = (Person) o1; Person p2 = (Person) o2; return p1.getAge() - p2.getAge(); } public boolean equals(Object obj) { return true; // for simplicity – always return true } }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Comparator - Example class AP10_4 { public static void main(String s[]) { Person data[] = new Person[5]; data[0] = new Person("LAU Tak Wah, Andy", 43); data[1] = new Person("LAI Ming, Leon", 33); data[2] = new Person("Cheung Hok Yau, Jacky", 50); data[3] = new Person("KWOK Fu Shing, Arron", 26); data[4] = new Person("CHAN Tai Man, Johnny", 44); int N = data.length; int i; Arrays.sort(data, new ByAgeComparator()); System.out.print("\nData items in ascending order\n"); for (i = 0; i <= N - 1; i++) System.out.println(data[i].getName()+ " " + data[i].getAge()); } }