Download presentation
Presentation is loading. Please wait.
57
max comparisons n n / 2 n / 2 n / 4 n / 4 … n / 4 n / 4 n / 4 n / 4n n / 2 n / 2n nn
58
FOR MERGE SORT, worstTime(n) IS O(n log n) THEREFORE averageTime(n) IS O(n log n)
73
// Postcondition: a is in ascending order. The worstTime(n) is // O(n * n), and averageTime(n) is O(n log n). public static void sort (int[ ] a) { sort1(a, 0, a.length); } // method sort Quick Sort
74
// Postcondition: the array x, from index off (inclusive) to index // off + len (exclusive), is in ascending order. private static void sort1(int x[ ], int off, int len);
75
IF len < 7, USE INSERTION SORT OTHERWISE, PARTITION ABOUT A pivot ELEMENT
76
IF len = 7, pivot = x [off + len / 2] ; IF 7 < len <= 40, pivot = median of x [off], x [off + len / 2], x [off + len – 1] IF len > 40, SPLIT INTO 3 SEGMENTS, TAKE MEDIAN OF EACH SEGMENT; pivot = median of the 3 medians
79
int v = x[m];// v is the pivot int b = off, c = off + len - 1; while(true) { while (b <= c && x[b] <= v) b++; while (c >= b && x[c] >= v) c--; if (b > c) break; swap(x, b++, c--); } sort1 (x, off, c - off + 1); sort1 (x, b, len - b);
88
int v = x[m]; // Establish Invariant: v* ( v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.