publicclassQuick{ // quick sort java implement. publicstaticvoidquickSort(Comparable[] a){ sort(a, 0, a.length-1); assertisSorted(a); } privatestaticvoidsort(Comparable[] a, int lo, int hi){ if (hi <= lo) return; int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); } privatestaticvoidpartition(Comparable[] a, int lo, int hi){ int i = lo; int j = hi + 1; Comparable v = a[lo]; while (true) { while (less(a[++i], v)) { if (lo == hi) break; } while (less(v, a[--j])) { if (j == lo) break; // redundant since a[lo] is sentinel. } // Check if pointers cross. if (j <= i) break; exch(a, i, j); } exch(a, lo, j); return j; } }
publicstaticvoidquickSortImproved(Comparable[] a){ sort(a, 0, a.length-1); assertisSorted(a); } private staic voidsort(Comparable[] a, int lo, int hi){ dealPivot(a, lo, hi); int i = lo; int j = hi - 1; Comparable v = a[hi - 1]; // set the pivot at hi -1 as a sentinel. while (true) { while (less(a[++i], v)) { if (i == hi-1) break; // redundant since a[hi - 1] is sentinel. } while (j > lo && less(v, a[--j])) { } // check if pointers cross. if (j <= i) break; exch(a, i, j); } if (i < hi-1) { exch(a, i, hi - 1); } sort(a, lo, i - 1); sort(a, i + 1, hi); } // 三取样并将切分元素放在数组末尾 privatestaticvoiddealPivot(Comparable[] a, int lo, int hi){ int mid = lo + (hi - lo) / 2; if (less(a[mid], a[lo])) exch(a, lo, mid); if (less(a[hi], a[lo])) exch(a, lo, hi); if (less(a[hi], a[mid])) exch(a, mid, hi); // put the pivot to hi - 1 as a sentinel. exch(a, mid, hi - 1); }
publicstaticvoidquickSort(Comparable[] a){ sort(a, 0, a.length-1); assertisSorted(a); } privatestaticvoidsort(Comparable[] a, int lo, int hi){ if (hi <= lo) return; Comparable v = a[lo]; int lt = lo; int i = lo + 1; int gt = hi; while (i <= gt) { if (less(a[i], v)) exch(a, i++, lt++); elseif (less(v, a[i])) exch(a, gt--, i); else i++; } // since a[lt .. i-1] is sorted. // sort the other subarrays recursively. sort(a, lo, lt-1); sort(a, gt+1, hi); }