Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 7 Sorting.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 7 Sorting."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 7 Sorting Algorithms Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Insertion Sort Each pass inserts a new element into a sorted sublist. Each pass inserts a new element into a sorted sublist. The insertion sort does not perform exchanges. Items larger than the target slide to the right until the algorithm reaches the insertion point. The insertion sort does not perform exchanges. Items larger than the target slide to the right until the algorithm reaches the insertion point.

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Illustration of Insertion Sort

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Outline of the Insertion Sort Algorithm Start by assuming that the first element is in its correct position. Start by assuming that the first element is in its correct position. For a general pass i (1 ≤ i ≤ n-1), the elements in the range from 0 to i-1 are already sorted. For a general pass i (1 ≤ i ≤ n-1), the elements in the range from 0 to i-1 are already sorted. Insert target = arr[i] into the range [0,i-1] by sliding elements to the right until space for target has been opened up. Copy target into its position. Insert target = arr[i] into the range [0,i-1] by sliding elements to the right until space for target has been opened up. Copy target into its position.

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. insertionSort() Method // sort an array of elements using insertion sort public static > void insertionSort(T[] arr) { int i, j, n = arr.length; T target; // place element at index i into the sublist // from index 0 to i-1 where 1 <= i < n, // so it is in the correct position for (i = 1; i < n; i++) { // index j scans down list from index i // looking for correct position to locate // target; assigns it to arr at index j j = i; target = arr[i];

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. insertionSort() Method (concluded) // locate insertion point by scanning downward // as long as target < arr[j] and we have not // encountered the beginning of the array while (j > 0 && target.compareTo(arr[j-1]) < 0) { // shift elements up list to make // room for insertion arr[j] = arr[j-1]; j--; } // the location is found; insert target arr[j] = target; }

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Insertion Sort Efficiency Best case running time is O(n) and occurs when the array is already sorted. Best case running time is O(n) and occurs when the array is already sorted. The worst and average case running times are O(n 2 ). The worst and average case running times are O(n 2 ). The insertion sort is very efficient with the array is "almost sorted". The insertion sort is very efficient with the array is "almost sorted". The insertion sort is the best of the quadratic sorting algorithms. The insertion sort is the best of the quadratic sorting algorithms.

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Divide and Conquer Algorithms Divide a problem into several smaller instances of the same problem, ideally of about the same size. Divide a problem into several smaller instances of the same problem, ideally of about the same size. Solve the smaller instances, normally using recursion. Solve the smaller instances, normally using recursion. For some problems, combine the solution to the smaller instances to solve the original problem. For some problems, combine the solution to the smaller instances to solve the original problem.

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Examples of Divide and Conquer Algorithms Binary search Binary search Drawing a ruler Drawing a ruler Merge sort and quicksort in this chapter. Merge sort and quicksort in this chapter. Binary tree traversals (Chapter 16) Binary tree traversals (Chapter 16)

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Sort Sort an array with n elements by dividing it into two halves with index ranges [0,n/2) and [n/2, n-1], sorting each half recursively, and then merging the two smaller sorted arrays into a single sorted array. Sort an array with n elements by dividing it into two halves with index ranges [0,n/2) and [n/2, n-1], sorting each half recursively, and then merging the two smaller sorted arrays into a single sorted array. The merging process involves using a temporary array with n elements. The merging process involves using a temporary array with n elements.

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Algorithm Start with array arr having n elements and create an array, tempArr, with n elements. Start with array arr having n elements and create an array, tempArr, with n elements. Let mid = (first + last)/2, and assume that ranges [first, mid) and [mid, last) are sorted. Let integers indexA = first and indexB = mid. Let mid = (first + last)/2, and assume that ranges [first, mid) and [mid, last) are sorted. Let integers indexA = first and indexB = mid.

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Algorithm (continued) Move indexA through [first, mid), and indexB through [mid, last), copying the smallest of arr[indexA] and arr[indexB] to position indexC in tempArr. Move indexA through [first, mid), and indexB through [mid, last), copying the smallest of arr[indexA] and arr[indexB] to position indexC in tempArr. Stop when indexA = mid or indexB = last. Stop when indexA = mid or indexB = last. Elements will remain in one sublist. Copy the tail of the sublist to tmpArr. Elements will remain in one sublist. Copy the tail of the sublist to tmpArr.

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Illustration Step 1

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Illustration Step 2

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Illustration Step 3

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Illustration Steps 4-7

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Illustration Steps 8-9

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Merge Illustration Conclusion The merge algorithm concludes by copying the elements from tempArr back to the original array, starting at index first.

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. General Sort Methods The Arrays class provides two versions of the method sort(), which implements the megesort algorithm. The Arrays class provides two versions of the method sort(), which implements the megesort algorithm. One version has an Object array arr as its parameter. One version has an Object array arr as its parameter. The other version is generic and specifies arr as an array of type T. The other version is generic and specifies arr as an array of type T. Both methods call the private method msort() that carries out the mergesort algorithm. Both methods call the private method msort() that carries out the mergesort algorithm.

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. sort() - with Object array public static void sort(Object[] arr) { // create a temporary array to store // partitioned elements Object[] tempArr = arr.clone(); // call msort with arrays arr and tempArr along // with the index range msort(arr, tempArr, 0, arr.length); }

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. sort() - Generic version public static > void sort(T[] arr) { // create a temporary array to store // partitioned elements T[] tempArr = (T[])arr.clone(); // call msort with arrays arr and tempArr along // with the index range msort(arr, tempArr, 0, arr.length); }

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The msort() Method Create two half-lists by computing the index midpt, representing the midpoint of the index range: int midpt = (last + first)/2; Create two half-lists by computing the index midpt, representing the midpoint of the index range: int midpt = (last + first)/2; Call msort for the index range [first, mid) and for the index range [mid, last). Call msort for the index range [first, mid) and for the index range [mid, last). When returning from the recursive calls, apply the merge algorithm to the range [first, last). When returning from the recursive calls, apply the merge algorithm to the range [first, last).

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Tracing the msort() Algorithm

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. msort() Notes A singleton sublist is already sorted. Such a list has index range [first, first+1), where last = first + 1. The recursive process continues only as long as first+1 < last. A singleton sublist is already sorted. Such a list has index range [first, first+1), where last = first + 1. The recursive process continues only as long as first+1 < last. Do not merge if arr[mid-1] < arr[mid]. Do not merge if arr[mid-1] < arr[mid].

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.msort() private static void msort(Object[] arr, Object[] tempArr, int first, int last) { // if the sublist has more // than 1 element continue if (first + 1 < last) { // for sublists of size 2 or more, call msort() // for the left and right sublists and then // merge the sorted sublists using merge() int midpt = (last + first) / 2; msort(arr, tempArr, first, midpt); msort(arr, tempArr, midpt, last);

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. msort() (continued) // if list is already sorted, just copy from // src to dest; this is an optimization that // results in faster sorts for nearly // ordered lists if (((Comparable)arr[midpt-1]).compareTo (arr[midpt]) <= 0) return; // the elements in the ranges (first,mid) // and (mid,last) are ordered; merge the // ordered sublists into an ordered sequence // in the range (first,last) using // the temporary array int indexA, indexB, indexC;

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. msort() (continued) // set indexA to scan sublist A // with range (first, mid) // and indexB to scan sublist B // with range (mid, last) indexA = first; indexB = midpt; indexC = first; // while both sublists are not exhausted, // compare arr[indexA] and arr[indexB]; // copy the smaller to tempArr while (indexA < midpt && indexB < last) { if (((Comparable)arr[indexA]).compareTo (arr[indexB]) < 0) { // copy to tempArr tempArr[indexC] = arr[indexA]; // increment indexA indexA++; }

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. msort() (continued) else { // copy to tempArr tempArr[indexC] = arr[indexB]; // increment indexB indexB++; } // increment indexC indexC++; } // copy the tail of the sublist // that is not exhausted while (indexA < midpt) { // copy to tempArr tempArr[indexC] = arr[indexA]; indexA++; indexC++; }

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. msort() (concluded) while (indexB < last) { // copy to tempArr tempArr[indexC] = arr[indexB]; indexB++; indexC++; } // copy elements from temporary // array to original array for (int i = first; i < last; i++) arr[i] = tempArr[i]; }

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Recursion Tree for Merge Sort

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Efficiency of Merge Sort Add up the number of comparisons done at each level of the recursion tree of height (int)log 2 n. Add up the number of comparisons done at each level of the recursion tree of height (int)log 2 n. At each level i in the tree, a merge involves n/2 i elements and requires less than n/2 i comparisons. The combined 2 i merges at level i require less than 2 i * (n/2 i ) = n comparisons. At each level i in the tree, a merge involves n/2 i elements and requires less than n/2 i comparisons. The combined 2 i merges at level i require less than 2 i * (n/2 i ) = n comparisons. The worst case running time is O(n log 2 n). The worst case running time is O(n log 2 n).

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Uses divide-and-conquer strategy. Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot in its final position in such a way that every value to the left of the pivot is ≤ pivot and every value to the right of the pivot is ≥ pivot. The algorithm locates the pivot in its final position in such a way that every value to the left of the pivot is ≤ pivot and every value to the right of the pivot is ≥ pivot. Unlike mergesort, quicksort is an in-place sorting algorithm. Unlike mergesort, quicksort is an in-place sorting algorithm.

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (1) Choose as pivot the element at index mid = (first + last)/2. The algorithm separates the elements of arr into two sublists, S l and S h. Sublist S l is the lower sublist and contains the elements ≤ pivot. The higher sublist, S h, contains the elements ≥ pivot. Choose as pivot the element at index mid = (first + last)/2. The algorithm separates the elements of arr into two sublists, S l and S h. Sublist S l is the lower sublist and contains the elements ≤ pivot. The higher sublist, S h, contains the elements ≥ pivot. // pivot = arr[mid] where mid = (last + first)/2 mid = (10 + 0)/5 = 5 pivot = arr[5] = 500;

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (2) Exchange arr[first] and arr[mid] and set up a scan of the list with index range [first+1, last). The index scanUp starts at position first+1 and moves up the list, identifying the elements in sublist S l. The index scanDown starts at position last -1 and moves down the list, identifying elements in sublist S h. Exchange arr[first] and arr[mid] and set up a scan of the list with index range [first+1, last). The index scanUp starts at position first+1 and moves up the list, identifying the elements in sublist S l. The index scanDown starts at position last -1 and moves down the list, identifying elements in sublist S h.

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (3) The scanning process begins with index scanUp and looks for the first element that is ≥ pivot. Such an element will ultimately belong in the upper sublist S h. The scanning process begins with index scanUp and looks for the first element that is ≥ pivot. Such an element will ultimately belong in the upper sublist S h. Index scanDown moves down the list looking for an element that is ≤ pivot. The element will ultimately belong in the lower sublist S l. Index scanDown moves down the list looking for an element that is ≤ pivot. The element will ultimately belong in the lower sublist S l.

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (4) The pair of elements, referenced by scanUp and scanDown are in the wrong sublists; arr[scanUp]  pivot and arr[scanDown]  pivot. Exchange the elements at the two positions and then update the two indices so that the scan with index scanUp can resume. The pair of elements, referenced by scanUp and scanDown are in the wrong sublists; arr[scanUp]  pivot and arr[scanDown]  pivot. Exchange the elements at the two positions and then update the two indices so that the scan with index scanUp can resume. // exchange elements and thus place them in the proper sublists temp = arr[scanUp]; arr[scanUp] = arr[scanDown]; arr[scanDown] = temp; scanUp++;// set scanUp at next element up the list scanDown--;// set scanDown at next element down the list

37 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (5)

38 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (6) The two scans with indices scanUp and scanDown work in tandem and locate the next pair of elements that must be repositioned to form the lower and upper sublists. In the process, the two indices move toward each other until they either land at the same position or pass one another (scanDown  scanUp). The two scans with indices scanUp and scanDown work in tandem and locate the next pair of elements that must be repositioned to form the lower and upper sublists. In the process, the two indices move toward each other until they either land at the same position or pass one another (scanDown  scanUp).

39 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (7) Resume scanning up the list. scanUp halts at element arr[4] = 550  500. scanDown halts at arr[7] = 350  500. Elements arr[4] and arr[7] are in the wrong sublists. Exchange the elements and update the indices to positions 5 and 6.

40 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (8) scanUp moves up the list, halting at position 5 (arr[5] = 800) and scanDown moves down the list, halting at position 6 (arr[6]=400). An exchange of elements and updates to the indices leave scanUp at position 6 and scanDown at position 5.

41 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Partitioning a List (9) The partition process terminates when scanDown ≤ scanUp. The partition process terminates when scanDown ≤ scanUp. The index scanDown is the index for the pivot in the array. The index scanDown is the index for the pivot in the array. Exchange arr[0] and arr[scanDown] to correctly position the pivot in the list. Exchange arr[0] and arr[scanDown] to correctly position the pivot in the list.

42 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Recursive Descent Let the variable pivotLoc denote the index of the pivot. Recursive steps continue the partitioning process on S l with index range [first, pivotLoc) and S h with index range [pivotLoc+1, last). Let the variable pivotLoc denote the index of the pivot. Recursive steps continue the partitioning process on S l with index range [first, pivotLoc) and S h with index range [pivotLoc+1, last).

43 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Recursive Descent (continued) Sublist S l : {400, 150, 300, 450, 350} with index range [0, 5). mid = (0 + 5)/2 = 2 pivot = arr[2] = 300 1-element sublist Further processing required for {400, 450, 350}

44 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Recursive Descent (continued) Sublist Sh: {800, 550, 650, 900} with index range [6, 10) mid = (6 + 10)/2 = 8 pivot = arr[8] = 650 1-element sublist Further processing required for {800, 900}

45 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Recursive Descent (continued)

46 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Recursive Descent (concluded)

47 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. pivotIndex() The method public static > int pivotIndex(T[] arr, int first, int last) The method public static > int pivotIndex(T[] arr, int first, int last) takes array arr and index range [first,last) and returns the index of the pivot after partitioning the range.

48 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. pivotIndex() (continued) public static > int pivotIndex(T[] arr, int first, int last) { // index for the midpoint of (first, last) and // the indices that scan the index range in tandem int mid, scanUp, scanDown; // pivot value and object used for exchanges T pivot, temp; if (first == last) // empty sublist return last; else if (first == last-1) // 1-element sublist return first; else { mid = (last + first)/2; pivot = arr[mid];

49 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. pivotIndex() (continued) // exchange the pivot and the low end of // the range and initialize the indices // scanUp and scanDown arr[mid] = arr[first]; arr[first] = pivot; scanUp = first + 1; scanDown = last - 1; // manage the indices to locate elements // that are in the wrong sublist; stop when // scanDown <= scanUp for(;;) { // move up the lower sublist; continue // so long as scanUp is less than or // equal to scanDown and the array // value is less than pivot while (scanUp <= scanDown && arr[scanUp].compareTo(pivot) < 0) scanUp++;

50 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. pivotIndex() (continued) // move down the upper sublist so long // as the array value is greater // than the pivot while (pivot.compareTo(arr[scanDown]) < 0) scanDown--; // if indices are not in their sublists, // partition complete if (scanUp >= scanDown) break; // indices are still in their sublists // and identify two elements in wrong // sublists; exchange temp = arr[scanUp]; arr[scanUp] = arr[scanDown]; arr[scanDown] = temp;

51 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. pivotIndex() (concluded) scanUp++; scanDown--; } // copy pivot to index (scanDown) that // partitions sublists and return scanDown arr[first] = arr[scanDown]; arr[scanDown] = pivot; return scanDown; }

52 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.quicksort() // sort arr using quicksort public static > void quicksort(T[] arr) { qsort(arr, 0, arr.length); } quicksort() takes an array arr of generic type as its argument and sorts the array by calling the private method qsort() with the index range [0, arr.length). quicksort() takes an array arr of generic type as its argument and sorts the array by calling the private method qsort() with the index range [0, arr.length).

53 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. qsort() The method qsort() implements the recursive quicksort algorithm. The method qsort() implements the recursive quicksort algorithm. Recursively partition the elements in the index range into smaller and smaller sublists, terminating when the size of a list is 0 or 1. Recursively partition the elements in the index range into smaller and smaller sublists, terminating when the size of a list is 0 or 1. For efficiency, handle a list of size 2 by simply comparing the elements and making an exchange if necessary. For efficiency, handle a list of size 2 by simply comparing the elements and making an exchange if necessary.

54 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. qsort() (continued) For larger lists, call pivotIndex() to reorder the elements and determine the index, pivotLoc, for the pivot. Make two calls to qsort(). The first call uses the arguments first and pivotLoc to specify the index range for the lower sublist. The second call uses the arguments pivotLoc+1 and last to specify the index range for the upper sublist. For larger lists, call pivotIndex() to reorder the elements and determine the index, pivotLoc, for the pivot. Make two calls to qsort(). The first call uses the arguments first and pivotLoc to specify the index range for the lower sublist. The second call uses the arguments pivotLoc+1 and last to specify the index range for the upper sublist.

55 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. qsort() (continued) private static > void qsort(T[] arr, int first, int last) { // index of the pivot int pivotLoc; // temp used for an exchange in a 2-element sublist T temp; // if the range is not at least two elements, return if (last - first <= 1) return; // if sublist has two elements, compare arr[first] and // arr[last-1] and exchange if necessary else if (last - first == 2) {

56 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. qsort() (concluded) if (arr[last-1].compareTo(arr[first]) < 0) { temp = arr[last-1]; arr[last-1] = arr[first]; arr[first] = temp; } return; } else { pivotLoc = pivotIndex(arr, first, last); // make the recursive call qsort(arr, first, pivotLoc); // make the recursive call qsort(arr, pivotLoc +1, last); }

57 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time of Quicksort The average case running time is O(n log 2 n). The average case running time is O(n log 2 n). The best case occurs when the array is already sorted. The best case occurs when the array is already sorted.

58 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time of Quicksort (continued) Quicksort is efficient even when the array is in descending order. Quicksort is efficient even when the array is in descending order.

59 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time of Quicksort (concluded) The worst-case occurs when the pivot consistently is the largest or smallest element in its sublist. In this case, the running time is O(n 2 ). This case is highly unlikely to occur. The worst-case occurs when the pivot consistently is the largest or smallest element in its sublist. In this case, the running time is O(n 2 ). This case is highly unlikely to occur.

60 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Comparison of Sorting Algorithms An inversion in an array, arr, is an ordered pair (arr[i], arr[j]), i arr[j]. When sorting in ascending order, arr[i] and arr[j] are out of order. An inversion in an array, arr, is an ordered pair (arr[i], arr[j]), i arr[j]. When sorting in ascending order, arr[i] and arr[j] are out of order. To sort in better than quadratic running time, a sorting algorithm must compare and exchange non ‑ adjacent elements and remove more than one inversion with each comparison. To sort in better than quadratic running time, a sorting algorithm must compare and exchange non ‑ adjacent elements and remove more than one inversion with each comparison.

61 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Comparsion of Sorting Algorithms (concluded) The O(n 2 ) sorting algorithms such as selection and insertion sort generally remove one inversion with each iteration. The O(n 2 ) sorting algorithms such as selection and insertion sort generally remove one inversion with each iteration. The O(n log 2 n) sorting algorithms such as quicksort and merge sort, compare nonadjacent elements and generally remove more than one inversion with each iteration. The O(n log 2 n) sorting algorithms such as quicksort and merge sort, compare nonadjacent elements and generally remove more than one inversion with each iteration.

62 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 7.1 import java.util.Random; import ds.util.Arrays; import ds.time.Timing; public class Program7_1 { // types of sorts we will test enum Sorts {mergesort, quicksort, insertionsort}; public static void main(String[] args) { final int SIZE = 75000; Integer[] arr1 = new Integer[SIZE], arr2 = new Integer[SIZE], arr3 = new Integer[SIZE]; int rndNum, i; Random rnd = new Random();

63 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 7.1 (continued) // load each array with the same // sequence of SIZE random numbers // in the range 0 to 999999 for (i=0; i < SIZE; i++) { rndNum = rnd.nextInt(1000000); arr1[i] = arr2[i] = arr3[i] = rndNum; } // call timeSort() with each sort type timeSort(arr1, Sorts.mergesort, "Merge sort"); timeSort(arr2, Sorts.quicksort, "Quick sort"); timeSort(arr3, Sorts.insertionsort, "Insertion sort"); } // output the first and last 3 // elements in a sorted array public static void outputFirst_Last(Object[] arr) { // capture array size in n int i, n = arr.length;

64 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 7.1 (continued) // output first 3 elements and last 3 elements for (i=0;i < 3;i++) System.out.print(arr[i] + " "); System.out.print("... "); for (i=n-3; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // post the time with a description // of the sort type public static > void timeSort(T[] arr, Sorts sortType, String sortName) { // create Timing object t and set at // start of sort Timing t = new Timing(); double timeRequired; t.start();

65 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 7.1 (concluded) // execute the kind of sort // specified by sortType switch(sortType) { case mergesort: Arrays.sort(arr); break; case quicksort: Arrays.quicksort(arr); break; case insertionsort: Arrays.insertionSort(arr); break; } // stop timing and capture the // elapsed time for the sort timeRequired = t.stop(); // display output with the sort type and time outputFirst_Last(arr); System.out.print(" " + sortName + " time is " + timeRequired + "\n\n"); }

66 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 7.1 (Run) Run: 26 38 47... 999980 999984 999984 Merge sort time is 0.109 26 38 47... 999980 999984 999984 Quick sort time is 0.078 26 38 47... 999980 999984 999984 Insertion sort time is 100.611

67 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Finding the k th Largest Element The median is a value M such that half the array elements are = M. Finding a median is a special case of a more general problem that locates the kth largest element of an array. The median is a value M such that half the array elements are = M. Finding a median is a special case of a more general problem that locates the kth largest element of an array. Can solve the problem by first sorting the array and then simply accessing the element at position k. Running time is O(n log 2 n) is we use quicksort or mergesort. Can solve the problem by first sorting the array and then simply accessing the element at position k. Running time is O(n log 2 n) is we use quicksort or mergesort.

68 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Finding the k th Largest Element (continued) For more efficient solution than sorting, locate the position of the k th -largest value by partitioning the elements into two disjoint sublists. The lower sublist contains k elements that are ≤ to the k th -largest and the upper sublist contains elements that are ≥ the k th -largest. The elements in the sublists do not need to be ordered. For more efficient solution than sorting, locate the position of the k th -largest value by partitioning the elements into two disjoint sublists. The lower sublist contains k elements that are ≤ to the k th -largest and the upper sublist contains elements that are ≥ the k th -largest. The elements in the sublists do not need to be ordered.

69 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Finding the k th Largest Element (continued) Apply pivoting technique from the quicksort algorithm to create the partition. Apply pivoting technique from the quicksort algorithm to create the partition. The algorithm is recursive. Compute index = pivotIndex(). If index == k, done; otherwise, call pivotIndex() with range [first, index) if k index. The algorithm is recursive. Compute index = pivotIndex(). If index == k, done; otherwise, call pivotIndex() with range [first, index) if k index.

70 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.findKth() public static > void findKth(T[] arr, int first, int last, int k) { int index; // partition range (first, last) in arr about the // pivot arr[index] index = pivotIndex(arr, first, last); // if index == k, we are done. kth largest is arr[k] if (index == k) return; else if(k < index) // search in lower sublist (first, index) findKth(arr, first, index, k); else // search in upper sublist (index+1, last) findKth(arr, index+1, last, k); }

71 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running time of findKth() The running time is O(n). This is superior to the O(n log 2 n) effort required if the array is first sorted. The running time is O(n). This is superior to the O(n log 2 n) effort required if the array is first sorted.


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 7 Sorting."

Similar presentations


Ads by Google