function quickSort(array: number[], low: number, high: number) {if (low >= high) return;
const pivot = array[high];
let i = low;
for (let j = low; j < high; j++) { if (array[j] < pivot) {[array[i], array[j]] = [array[j], array[i]];
i++;
}
}
[array[i], array[high]] = [array[high], array[i]];
quickSort(array, low, i - 1);
quickSort(array, i + 1, high);
}
Start: 24 values in random order. quickSort(a, 0, 23) is called on the whole range.
Understanding Quick sort
The idea
Quick sort picks one element as the pivot and rearranges the range so everything smaller sits on its left and everything larger on its right. After that partition the pivot is in its final position, and the algorithm calls itself on the two sides until every range has one element.
The Lomuto partition shown here uses the last element as the pivot and walks the range once, swapping smaller elements to the frontier i. Hoare’s version uses two indices closing in from both ends and does about three times fewer swaps.
The four stages
Complexity
Versus its siblings
Pseudocode
QUICKSORT(array, low, high)
if low ≥ high: return
pivot ← array[high]; i ← low
for j ← low to high − 1
if array[j] < pivot: swap array[i], array[j]; i ← i + 1
swap array[i], array[high]
QUICKSORT(array, low, i − 1)
QUICKSORT(array, i + 1, high)
When to use
Pitfalls
History
Tony Hoare designed quick sort in 1959, at 25, while at Moscow State University working on machine translation and needing to sort dictionary words. He published it in 1961. In 2009 Vladimir Yaroslavskiy proposed the dual-pivot version that Java has used since version 7.