Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p.597-604 Selection Sort ; Reading p.342-346.

Similar presentations


Presentation on theme: "1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p.597-604 Selection Sort ; Reading p.342-346."— Presentation transcript:

1 1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p.597-604 Selection Sort ; Reading p.342-346 Insertion Sort Bubble (or Exchange) Sort

2 2 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search Searching is the process of determining whether or not a given value exists in a data structure or a storage media. We discuss two searching methods on one-dimensional arrays: linear search and binary search. The linear (or sequential) search algorithm on an array is: –Sequentially scan the array, comparing each array item with the searched value. –If a match is found; return the index of the matched element; otherwise return –1. The algorithm translates to the following Java method: public static int linearSearch(Object[] array, Object key){ for(int k = 0; k < array.length; k++) if(array[k].equals(key)) return k; return -1; } Note: linear search can be applied to both sorted and unsorted arrays.

3 3 © 2006 Pearson Addison-Wesley. All rights reserved Binary Search Binary search uses a recursive method to search an array to find a specified value The array must be a sorted array: a[0]≤a[1]≤a[2]≤... ≤ a[finalIndex] If the value is found, its index is returned If the value is not found, -1 is returned Note: Each execution of the recursive method reduces the search space by about a half

4 4 © 2006 Pearson Addison-Wesley. All rights reserved Binary Search An algorithm to solve this task looks at the middle of the array or array segment first If the value looked for is smaller than the value in the middle of the array –Then the second half of the array or array segment can be ignored –This strategy is then applied to the first half of the array or array segment

5 5 © 2006 Pearson Addison-Wesley. All rights reserved Binary Search If the value looked for is larger than the value in the middle of the array or array segment –Then the first half of the array or array segment can be ignored –This strategy is then applied to the second half of the array or array segment If the value looked for is at the middle of the array or array segment, then it has been found If the entire array (or array segment) has been searched in this way without finding the value, then it is not in the array

6 6 © 2006 Pearson Addison-Wesley. All rights reserved Pseudocode for Binary Search

7 7 © 2006 Pearson Addison-Wesley. All rights reserved Recursive Method for Binary Search

8 8 © 2006 Pearson Addison-Wesley. All rights reserved Execution of the Method search (Part 1 of 2)

9 9 © 2006 Pearson Addison-Wesley. All rights reserved Execution of the Method search (Part 1 of 2)

10 10 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method 1.There is no infinite recursion On each recursive call, the value of first is increased, or the value of last is decreased If the chain of recursive calls does not end in some other way, then eventually the method will be called with first larger than last

11 11 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method 2.Each stopping case performs the correct action for that case If first > last, there are no array elements between a[first] and a[last], so key is not in this segment of the array, and result is correctly set to - 1 If key == a[mid], result is correctly set to mid

12 12 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method 3.For each of the cases that involve recursion, if all recursive calls perform their actions correctly, then the entire case performs correctly If key < a[mid], then key must be one of the elements a[first] through a[mid-1], or it is not in the array The method should then search only those elements, which it does The recursive call is correct, therefore the entire action is correct

13 13 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method If key > a[mid], then key must be one of the elements a[mid+1] through a[last], or it is not in the array The method should then search only those elements, which it does The recursive call is correct, therefore the entire action is correct The method search passes all three tests: Therefore, it is a good recursive method definition

14 14 © 2006 Pearson Addison-Wesley. All rights reserved Efficiency of Binary Search The binary search algorithm is extremely fast compared to an algorithm that tries all array elements in order –About half the array is eliminated from consideration right at the start –Then a quarter of the array, then an eighth of the array, and so forth

15 15 © 2006 Pearson Addison-Wesley. All rights reserved Efficiency of Binary Search Given an array with 1,000 elements, the binary search will only need to compare about 10 array elements to the key value, as compared to an average of 500 for a serial search algorithm The binary search algorithm has a worst-case running time that is logarithmic: O(log n) –A serial search algorithm is linear: O(n) If desired, the recursive version of the method search can be converted to an iterative version that will run more efficiently

16 16 © 2006 Pearson Addison-Wesley. All rights reserved Iterative Version of Binary Search (Part 1 of 2)

17 17 © 2006 Pearson Addison-Wesley. All rights reserved Iterative Version of Binary Search (Part 2 of 2)

18 18 © 2006 Pearson Addison-Wesley. All rights reserved Sorting an Array A sort method takes in an array parameter a, and rearranges the elements in a, so that after the method call is finished, the elements of a are sorted in ascending order A selection sort accomplishes this by using the following algorithm: for (int index = 0; index < count; index++) Place the indexth smallest element in a[index]

19 19 © 2006 Pearson Addison-Wesley. All rights reserved Selection Sort (Part 1 of 2)

20 20 © 2006 Pearson Addison-Wesley. All rights reserved Selection Sort (Part 2 of 2)

21 21 © 2006 Pearson Addison-Wesley. All rights reserved SelectionSort Class (Part 1 of 5) public class SelectionSort { /** Precondition: count <= a.length; The first count indexed variables have values. Action: Sorts a so that a[0] <= a[1] <=... <= a[count - 1]. */

22 22 © 2006 Pearson Addison-Wesley. All rights reserved SelectionSort Class (Part 2 of 5) public static void sort(double[] a, int count) { int index, indexOfNextSmallest; for (index = 0; index < count - 1; index++) {//Place the correct value in a[index]: indexOfNextSmallest = indexOfSmallest(index, a, count); interchange(index,indexOfNextSmallest, a); //a[0]<=a[1]<=...<=a[index] and these are //the smallest of the original array //elements. The remaining positions contain //the rest of the original array elements. }

23 23 © 2006 Pearson Addison-Wesley. All rights reserved SelectionSort Class (Part 3 of 5) /** Returns the index of the smallest value among a[startIndex], a[startIndex+1],... a[numberUsed - 1] */ private static int indexOfSmallest(int startIndex, double[] a, int count) { double min = a[startIndex]; int indexOfMin = startIndex; int index;

24 24 © 2006 Pearson Addison-Wesley. All rights reserved SelectionSort Class (Part 4 of 5) for (index = startIndex + 1; index < count; index++) if (a[index] < min) { min = a[index]; indexOfMin = index; //min is smallest of a[startIndex] through //a[index] } return indexOfMin; }

25 25 © 2006 Pearson Addison-Wesley. All rights reserved SelectionSort Class (Part 5 of 5) /** Precondition: i and j are legal indices for the array a. Postcondition: Values of a[i] and a[j] have been interchanged. */ private static void interchange(int i, int j, double[] a) { double temp; temp = a[i]; a[i] = a[j]; a[j] = temp; //original value of a[i] }

26 26 © 2006 Pearson Addison-Wesley. All rights reserved Selection Sort (cont’d) To sort an array with k elements, Selection sort requires k – 1 passes. Example:

27 27 © 2006 Pearson Addison-Wesley. All rights reserved GeneralizedSelectionSort class: sort Method

28 28 © 2006 Pearson Addison-Wesley. All rights reserved GeneralizedSelectionSort class: sort Method

29 29 © 2006 Pearson Addison-Wesley. All rights reserved GeneralizedSelectionSort class: interchange Method

30 30 © 2006 Pearson Addison-Wesley. All rights reserved Sorting Arrays of Comparable

31 31 © 2006 Pearson Addison-Wesley. All rights reserved Sorting Arrays of Comparable

32 32 © 2006 Pearson Addison-Wesley. All rights reserved Sorting Arrays of Comparable

33 33 © 2006 Pearson Addison-Wesley. All rights reserved Insertion Sort The array is partitioned into 2 parts, sorted (on the left) and unsorted (on the right). Initially the sorted part has one element. In each pass, the first element of the unsorted part is inserted in the appropriate location in the sorted left block. The Insertion sort pseudo-code algorithm is: insertionSort(array){ for(i = 1; i < array.length; i++){ // array[i] is the element to be inserted temp = array[i]; insert temp in its proper location in the sorted subarray array[0]...array[i -1] } Inserting temp in its proper location involves two steps: Finding the position k where temp is to be inserted. Shifting each of the elements array[k]...array[i -1] to the right by one slot //inserting to maintain ascending order temp = array[i]; k = i; while(k > 0 && array[k - 1] > temp){ array[k] = array[k - 1]; // shift value at index k-1 to location with index k k--; } array[k] = temp; // insert array [i] at the right location with index k

34 34 © 2006 Pearson Addison-Wesley. All rights reserved Insertion Sort (cont’d) The following java method implements Insertion sort algorithm and sorts the array according to the comparator object. public static void insertionSort(Object[] array, Comparator comp){ int i,k; Object temp; for(i = 1; i < array.length ; i++){ temp = array[i]; k = i; while((k > 0)&& comp.compare(array[k-1],temp) > 0){ array[k] = array[k-1]; k--; } array[k] = temp; }

35 35 © 2006 Pearson Addison-Wesley. All rights reserved Insertion Sort (cont’d) To sort an array with k elements, Insertion sort requires k – 1 passes. Example:

36 36 © 2006 Pearson Addison-Wesley. All rights reserved Bubble Sort The basic idea is to compare two neighboring objects, and to swap them if they are in the wrong order During each pass, the largest object is pushed to the end of the unsorted sub-array. This will continue until the unsorted sub-array has one element. The Bubble (Exchange) sort pseudo-code algorithm is: bubbleSort(array){ numberOfPasses = 1; while(numberOfPasses < array.length){ for(k = 1; k <= array.length – numberOfPasses; k++) swap array[k-1] and array[k] if they are out of order; numberOfPasses++; } Note: If no swaps occur in a complete for loop, the array is sorted. A boolean variable may be used to terminate the while loop prematurely.

37 37 © 2006 Pearson Addison-Wesley. All rights reserved Bubble Sort (cont’d) public static void bubbleSort(Object[] array, Comparator comp){ int pass = 1; Object temp; boolean sorted; do{ sorted = true; for(int m = 1; m <= array.length - pass; m++){ if(comp.compare(array[m - 1], array[m]) > 0){ temp = array[m-1]; // swap neighbors atm and m-1 array[m-1] = array[m]; array[m] = temp; sorted = false; }} // end of for loop pass++; }while(! sorted); }

38 38 © 2006 Pearson Addison-Wesley. All rights reserved Bubble Sort (cont’d) To sort an array with k elements, Bubble sort requires k – 1 passes. Example:


Download ppt "1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p.597-604 Selection Sort ; Reading p.342-346."

Similar presentations


Ads by Google