template<class T> voidQuickSort(T *a, int n){ // Sort a[0:n-1] using quick sort. // Requires a[n] must have largest key. quickSort(a, 0, n-1); // 以数组第一个元素作为支点 }
template<class T> voidquickSort(T a[], int l, int r) {// Sort a[l:r], a[r+1] has large value.
if (l >= r) { return; }
int i = l, // left-to-right cursor j = r + 1; // right-to-left cursor T pivot = a[l];
// swap elements >= pivot on left side // with elements <= pivot on right side while (true) { while (a[++i] < pivot) { // find >= element on left side if (i == r) { break; } } while (a[--j] > pivot) { // find <= element on right side if (j == l) { break; } }
if (i >= j) { break; // swap pair not found } Swap(a[i], a[j]); }
// place pivot a[l] = a[j]; a[j] = pivot;
quickSort(a, l, j-1); // sort left segment quickSort(a, j+1, r); // sort right segment }
privatestaticvoidquickSort(int[] a, int begin, int end){ if (begin >= end) { return; }
int left = begin; int right = end; int pivot = a[begin]; // 首元素为支点
while (left != right) {
// search element smaller than pivot from right to left while (a[right] >= pivot && left < right) { right--; } // then search element bigger than pivot from left to right while (a[left] <= pivot && left < right) { left++; }
if (left < right) { Swapper.swap(a, left, right); } }
// put pivot into middle a[begin] = a[left]; a[left] = pivot;
quickSort(a, begin, left - 1); // sort left part quickSort(a, left + 1, end); // sort right part } }
privatestaticvoidquickSort(int[] a, int begin, int end){ if (begin >= end) { return; }
int left = begin; int right = end; // 随机确定支点的位置 int pivotInt = RANDOM.nextInt(end - begin + 1) + begin; int pivot = a[pivotInt]; //选定基准值后,将基准值的位置和最开头的位置交换,这样在右边留出连续空间,便于交换 Swapper.swap(a, pivotInt, begin);
while (left != right) {
// search element smaller than pivot from right to left while (a[right] >= pivot && left < right) { right--; } // then search element bigger than pivot from left to right while (a[left] <= pivot && left < right) { left++; }
if (left < right) { Swapper.swap(a, left, right); } }
// put pivot into middle a[begin] = a[left]; a[left] = pivot;
quickSort(a, begin, left - 1); // sort left part quickSort(a, left + 1, end); // sort right part } }