The key process in QuickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time.
Choose Pivot
Pick first element as pivot.
Pick last element as pivot.
Pick a random element as pivot.
Pick median as pivot.
C++ Code for QuickSort function:
voidquick_sort(intA[], intl, intr){ // only one elementif (l >= r) return; // choose median as pivotint pivot = A[l + r >> 1];int i = l - 1, j = r + 1;while (i < j) {do i ++ ; while (A[i] < pivot);do j -- ; while (A[j] > pivot);if (i < j) swap(A[i], A[j]); }quick_sort(A, l, j);quick_sort(A, j + 1, r);}
Idea:
Choose median element as pivot.
Using two pointers, left pointer points to the most left element - 1;
right pointer points to the most right element + 1.
left pointer move from lefe to right, until the element is greater and equal then pivot; right pointer move from right to left, until the element is less and equal then pivot.
swap() the value of two pointers points to.
Repeat 3 & 4 until left < right is no longer true.