Quicksort picks a pivot, then partitions: everything ≤ pivot goes left, everything > pivot goes right. After partitioning, the pivot sits at its FINAL position, no later step will ever move it. Recurse on the left side and the right side. Unlike merge sort, all the work happens BEFORE the recursion (partitioning), and there's no merge afterward.
In practice, quicksort is usually the fastest comparison sort: partitioning is a tight in-place loop with excellent cache behavior (it sweeps memory sequentially and writes near where it reads), and its partitioning does less data movement than merging. The catch is the worst case: consistently bad pivots (say, always the smallest element on sorted input with a naive last-element pivot) split n into 0 + (n−1), giving O(n²). Production implementations defend with random pivots or median-of-three, making the worst case astronomically unlikely.
Lomuto partition (pivot = last element)
function quickSort(arr, low = 0, high = arr.length - 1) {
if (low >= high) return arr; // 0 or 1 elements: sorted
const p = partition(arr, low, high);
quickSort(arr, low, p - 1); // left of pivot
quickSort(arr, p + 1, high); // right of pivot
return arr;
}
function partition(arr, low, high) {
const pivot = arr[high]; // last element (naive choice, see note)
let boundary = low; // end of the "<= pivot" region
for (let i = low; i < high; i++) {
if (arr[i] <= pivot) { // belongs in the left region
[arr[i], arr[boundary]] = [arr[boundary], arr[i]];
boundary++;
}
}
[arr[boundary], arr[high]] = [arr[high], arr[boundary]]; // pivot to its final home
return boundary; // pivot's final index
}Partition trace: [7, 2, 9, 4], pivot = 4
- 1
Sweep i = 0..2
7 > 4 skip; 2 ≤ 4 swap(2↔7) → [2, 7, 9, 4], boundary=1; 9 > 4 skip.
- 2
Place pivot
Swap arr[boundary]=7 with pivot 4 → [2, 4, 9, 7]. Pivot 4 is now at index 1, final position.
- 3
Recurse
Left side [2] (trivial), right side [9, 7] → partitions around 7 → [7, 9]. Done: [2, 4, 7, 9].
- 4
Invariant check
After partition: everything ≤ 4 left of index 1, everything > 4 right. That claim is the entire correctness argument, recursion just maintains it.
| Operation / case | Cost | Notes |
|---|---|---|
| Best & average case | O(n log n) | balanced partitions |
| Worst case | O(n²) | naive pivot + sorted/duplicate-heavy input |
| Space | O(log n) | recursion stack, in-place partitioning |
| Stable? | No | long-distance swaps reorder equal keys |