QUICK-SORT(A, start, end) Input : An array A index from 0 to A.size-1 start the first position to start sorting end the last position to sort Output: A will be ordered from start to end
- if start < end
- pivot ← partition(A, start, end)
- Quicksort(A, start, pivot-1)
- Quicksort(A, pivot+1, end)
PARTITION(A, start end) Input: an unordered Array from start to end Output: a position p that divides the array A[i] ≤ A[p] for all i < p A[i] ≥ A[p] for all i > p
- pivotValue ← A[end]
- pivotPoint ← start-1
- for i ← start to end -1
- if A[i] ≤ poviotValue
- pivotPoint ← pivotPoint + 1
- swap(A[i], A[pivotPoint];
- swap(A[end], A[pivotPoint+1];
pivotValue PivotPoint i A 0 1 2 3 4 5 6 4 -1 0 3 7 9 2 5 1 _ 4 is still at position 6 3 < 4, so swap 4 -1 1 3 7 9 2 5 1 _ 3 and 3 exchanged At this point notice The array less than 1 is small 4 0 1 3 7 9 2 5 1 _ 7 > 4, no action 4 0 2 3 7 9 2 5 1 _ 9 > 4, no action 4 0 3 3 7 9 2 5 1 _ 2 < 4, swap 4 1 3 3 2 9 7 5 1 _ 2 and 7 exchanged {3, 2} are less than the pivot value {9, 7} are greater than the pivot value {5, 1} are unknown 4 2 4 3 2 9 7 5 1 _ 5 > 4, no action 4 2 5 3 2 9 7 5 1 _ 1 < 4, swap 4 3 5 3 2 1 7 5 9 _ 1 and 9 exchanged At this point note The array [start, pivotPoint-1] is less than the pivot value The array [pivotPoint, end-1] is greater than the pivot point A[pivotPoint] can go to the end of the array where the pivot value is stored 4 3 5 3 2 1 4 5 9 7
In the beginning, the array less that pivot point (empty) contains values less than the pivot point The array pivotpoint and greater (the entire array) contains unclassified values