Presentation is loading. Please wait.

Presentation is loading. Please wait.

Searching and Sorting Linear Search Binary Search ; Reading p

Similar presentations


Presentation on theme: "Searching and Sorting Linear Search Binary Search ; Reading p"— Presentation transcript:

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

2 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. © 2006 Pearson Addison-Wesley. All rights reserved

3 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 © 2006 Pearson Addison-Wesley. All rights reserved

4 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 © 2006 Pearson Addison-Wesley. All rights reserved

5 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 © 2006 Pearson Addison-Wesley. All rights reserved

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

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

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

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

10 Checking the search Method
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 © 2006 Pearson Addison-Wesley. All rights reserved

11 Checking the search Method
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 © 2006 Pearson Addison-Wesley. All rights reserved

12 Checking the search Method
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 © 2006 Pearson Addison-Wesley. All rights reserved

13 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 © 2006 Pearson Addison-Wesley. All rights reserved

14 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 © 2006 Pearson Addison-Wesley. All rights reserved

15 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 © 2006 Pearson Addison-Wesley. All rights reserved

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

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

18 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] © 2006 Pearson Addison-Wesley. All rights reserved

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

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

21 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]. */ © 2006 Pearson Addison-Wesley. All rights reserved

22 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. } © 2006 Pearson Addison-Wesley. All rights reserved

23 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; © 2006 Pearson Addison-Wesley. All rights reserved

24 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; © 2006 Pearson Addison-Wesley. All rights reserved

25 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] } © 2006 Pearson Addison-Wesley. All rights reserved

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

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

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

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

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

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

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

33 Insertion Sort The array is partitioned into 2 parts, sorted (on the left) and unsorted (on the right). Initially the unsorted 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 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 © 2006 Pearson Addison-Wesley. All rights reserved

34 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; © 2006 Pearson Addison-Wesley. All rights reserved

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

36 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. © 2006 Pearson Addison-Wesley. All rights reserved

37 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); } © 2006 Pearson Addison-Wesley. All rights reserved

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


Download ppt "Searching and Sorting Linear Search Binary Search ; Reading p"

Similar presentations


Ads by Google