// input: A[lo...hi-1], lo, hi // A[lo...hi-1]: array to be sorted // lo, hi: the region to be sorted is [lo, hi) // output: sorted arr QuickSort(A[lo...hi-1], lo, hi): if lo + 1 >= hi; then return // in this case, no element/ only one in the region, no need to sort end if mi := Partition(A, lo, hi) QuickSort(A, lo, mi) QuickSort(A, mi + 1, hi)
// output: index where pivot should locate Partition(A[lo...hi-1], lo, hi): pivot := A[hi-1]; // x \in [lo, i], A[x] < pivot i := lo - 1; // x \in [i+1, j), A[x] >= pivot j := lo while j < hi - 1; do if A[j]<pivot; then// then region gets bigger as i increased, and A[j] should be in A[lo..i] swap(A[j],A[i+1]) i = i + 1 end if j = j + 1 end loop //i + 1 should be the first index where element >= pivot swap(A[i+1],A[hi-1]); return i+1;
inlineint _partition(int *A, int lo, int hi) { int pivot = A[lo]; int i = lo; int j = hi - 1; //lo [lo+1, i] [i+1, j] [j+1,hi-1] while(i<j){ //in my version, there is no stipulation that j must move before i. while(i<j&&A[i+1]<pivot) ++i; while(i<j&&A[j]>=pivot) --j; if(i<j){ swap(A[i+1],A[j]); } } // now unknown region is empty, and j is the first index where A[j] >= pivot, //A[lo] = pivot, A[lo+1...i] < pivot // so A[i-1] is the last index where A[i-1] < pivot after exchange swap(A[i],A[lo]); return i; }
voidquickSort(int *A, int lo, int hi){ if (lo + 1 >= hi) { return; } int mi = _partition(A, lo, hi); quickSort(A, lo, mi); quickSort(A, mi+1, hi); }