functionquicksort(q) { var list less, pivotList, greater if length(q) ≤ 1 return q else { select a pivot value pivot from q for each x in q except the pivot element { if x < pivot then add x to less if x ≥ pivot then add x to greater } add pivot to pivotList return concatenate(quicksort(less), pivotList, quicksort(greater)) } }
// i必须从start开始,而不是 start + 1 int i = start, j = end; while (i < j) { // 必须先执行--j的操作 while (i < j && array[j] >= pivot) --j; while (i < j && array[i] <= pivot) ++i; if (i < j) { swap(array, i, j); } } // 移动pivot到正确位置 swap(array, start, i); return i; }
staticvoidquickSort(int[] array, int start, int end){ if (start >= end) { return; } int pivot = partition(array, start, end); quickSort(array, start, pivot - 1); quickSort(array, pivot + 1, end); }
staticintpartition(int[] array, int start, int end){ movePivotToStart(array, start, end); int pivot = array[start]; int i = start, j = end; while (i < j) { while (i < j && array[j] >= pivot) --j; while (i < j && array[i] <= pivot) ++i; if (i < j) { swap(array, i, j); } } swap(array, start, i); return i; }
staticvoidmovePivotToStart(int[] array, int start, int end){ int pivotIndex = start + new Random().nextInt(end - start); swap(array, pivotIndex, start); }
staticvoidswap(int[] array, int x, int y){ int tmp = array[x]; array[x] = array[y]; array[y] = tmp; }