4. Quicksort & Partitioning
Pick a pivot, partition, recurse — the fastest sort in practice
Merge sort is elegant and reliable, but in the real world most standard library sort functions use quicksort — or a hybrid that starts with it. Why? Because quicksort sorts in-place, has excellent cache locality, and despite a scary worst case, its average performance beats everything else in practice.
The idea is disarmingly simple: pick an element (the pivot), rearrange the array so everything smaller is on the left and everything larger is on the right, then do the same thing to each half. That rearrangement step — partitioning — is where all the action happens.
The Core Idea
Quicksort in three lines
- Choose a pivot — any element from the array.
- Partition — move elements so that everything ≤ pivot is on the left, everything ≥ pivot is on the right, and the pivot lands in its final sorted position.
- Recurse — quicksort the left part and the right part.
After partitioning, the pivot is in exactly the right place. It will never move again. Each recursive call shrinks the problem, and the base case is a subarray of length 0 or 1.
A Simple Example
Sorting [8, 3, 1, 7, 0, 10, 2] — pivot = last element (2)
Array: [8, 3, 1, 7, 0, 10, 2] pivot = 2
Step 1: Scan from left. 8 > 2, so it stays for now.
Step 2: 3 > 2, stays.
Step 3: 1 ≤ 2, swap 1 with 8 → [1, 3, 8, 7, 0, 10, 2]
Step 4: 7 > 2, stays.
Step 5: 0 ≤ 2, swap 0 with 3 → [1, 0, 8, 7, 3, 10, 2]
Step 6: 10 > 2, stays.
Step 7: Place pivot: swap 2 with 8 → [1, 0, 2, 7, 3, 10, 8]
↑
pivot in final position (index 2)
Left subarray: [1, 0] — recurse
Right subarray: [7, 3, 10, 8] — recurse
The pivot 2 is now at index 2 — exactly where it belongs in the sorted result. Everything to its left is smaller, everything to its right is larger.
Lomuto Partition Scheme
The simplest partitioning approach, attributed to Nico Lomuto. It always uses the last element as the pivot and maintains a boundary index i that tracks where the "small" elements end.
-
Set the boundary
Let
i = lo - 1. Everything at or before indexiwill be ≤ pivot. -
Scan left to right
For each element from
lotohi - 1: if the element is ≤ pivot, incrementiand swap the element witharr[i]. -
Place the pivot
Swap
arr[i + 1]witharr[hi](the pivot). Returni + 1as the pivot's final index.
Pseudocode (Lomuto)
function lomuto_partition(arr, lo, hi):
pivot = arr[hi]
i = lo - 1
for j from lo to hi - 1:
if arr[j] <= pivot:
i = i + 1
swap arr[i], arr[j]
swap arr[i + 1], arr[hi]
return i + 1
function quicksort(arr, lo, hi):
if lo < hi:
p = lomuto_partition(arr, lo, hi)
quicksort(arr, lo, p - 1)
quicksort(arr, p + 1, hi)
Hoare Partition Scheme
Tony Hoare — who invented quicksort in 1959 — used a different partitioning strategy. Two pointers start at opposite ends and walk toward each other, swapping elements that are on the wrong side. It does fewer swaps on average than Lomuto.
-
Choose a pivot value
Pick the first element (or any element). Don't remove it — just remember its value.
-
Walk two pointers inward
Move
iright untilarr[i] ≥ pivot. Movejleft untilarr[j] ≤ pivot. Ifi < j, swap them and continue. -
Return the partition boundary
When the pointers cross, return
j. Elements[lo..j]are ≤ pivot and[j+1..hi]are ≥ pivot.
Pseudocode (Hoare)
function hoare_partition(arr, lo, hi):
pivot = arr[lo]
i = lo - 1
j = hi + 1
loop:
do: i = i + 1
while arr[i] < pivot
do: j = j - 1
while arr[j] > pivot
if i >= j:
return j
swap arr[i], arr[j]
function quicksort_hoare(arr, lo, hi):
if lo < hi:
p = hoare_partition(arr, lo, hi)
quicksort_hoare(arr, lo, p)
quicksort_hoare(arr, p + 1, hi)
Lomuto vs Hoare
Lomuto is simpler to implement and reason about. Hoare does roughly 3x fewer swaps on average and handles duplicates more gracefully. Most production implementations use Hoare or a three-way variant.
Pivot Selection Strategies
The pivot choice determines how balanced the partition is — and therefore how fast the sort runs. An ideal pivot splits the array in half. A terrible pivot puts everything on one side.
| Strategy | How it works | Risk |
|---|---|---|
| First element | Use arr[lo] |
Worst case on already-sorted input |
| Last element | Use arr[hi] |
Same problem — sorted input is O(n²) |
| Random | Pick a random index in [lo, hi] |
No deterministic worst case; expected O(n log n) |
| Median-of-three | Take the median of first, middle, and last | Very reliable; defeats sorted/reverse-sorted input |
Median-of-three is the most popular choice in production code. It avoids the worst case on common inputs and adds negligible overhead.
The Worst Case: O(n²)
Quicksort's nightmare is a pivot that always lands at one extreme — producing one subarray of size n - 1 and another of size 0. This happens when the array is already sorted and you pick the first or last element as pivot.
Worst case: sorted array with last-element pivot
Array: [1, 2, 3, 4, 5] pivot = 5
Partition: [1, 2, 3, 4] | 5 | [] — nothing moved, n-1 comparisons
Array: [1, 2, 3, 4] pivot = 4
Partition: [1, 2, 3] | 4 | [] — n-2 comparisons
Array: [1, 2, 3] pivot = 3
Partition: [1, 2] | 3 | [] — n-3 comparisons
...and so on.
Total comparisons: (n-1) + (n-2) + ... + 1 = n(n-1)/2 = O(n²)
Instead of splitting the problem in half each time (log n levels), we peel off one element per level (n levels). That's O(n) levels × O(n) work per level = O(n²).
This is why pivot selection matters so much. Random pivots or median-of-three make the worst case astronomically unlikely.
Average Case: O(n log n)
When the pivot lands somewhere near the middle, each partition roughly halves the array. That gives us O(log n) levels of recursion, each doing O(n) total work across all partitions at that level — the same structure as merge sort.
Why quicksort beats merge sort in practice
- In-place: Quicksort needs only O(log n) stack space. Merge sort requires O(n) auxiliary memory to merge.
- Cache locality: Quicksort operates on contiguous memory, making excellent use of CPU caches. Merge sort's auxiliary buffer causes more cache misses.
- Low overhead: Partitioning is a tight loop with simple comparisons and swaps — no copying to temporary arrays.
- Branch prediction: The partition scan is predictable for the CPU, resulting in fewer pipeline stalls.
Quicksort vs Merge Sort
| Property | Quicksort | Merge Sort |
|---|---|---|
| Best case | O(n log n) | O(n log n) |
| Average case | O(n log n) | O(n log n) |
| Worst case | O(n²) | O(n log n) |
| Space | O(log n) stack | O(n) auxiliary |
| Stable? | No | Yes |
| In-place? | Yes | No (typically) |
| Cache behavior | Excellent | Good |
| Practical speed | Fastest on average | Slightly slower |
Where Quicksort Is Used
| Application | Details |
|---|---|
C's qsort() |
The C standard library sort — almost always a quicksort variant |
C++ std::sort |
Introsort: quicksort that falls back to heapsort if recursion goes too deep |
Java Arrays.sort |
Dual-pivot quicksort for primitives (by Vladimir Yaroslavskiy) |
Rust sort_unstable |
Pattern-defeating quicksort (pdqsort) — a modern hybrid |
| Quickselect | Find the k-th smallest element in O(n) average time — same partition idea, but only recurse on one side |
| Database query planners | Sorting intermediate results for ORDER BY, GROUP BY, and merge joins |
Key Takeaways
- Quicksort picks a pivot, partitions the array around it, and recurses on both halves
- Lomuto partition is simpler; Hoare partition does fewer swaps and is preferred in practice
- Pivot selection is critical — first/last element pivots degrade to O(n²) on sorted input
- Random or median-of-three pivot selection makes the worst case virtually impossible
- Average case is O(n log n) with excellent constant factors due to in-place operation and cache locality
- Most real-world standard library sorts are quicksort variants (introsort, dual-pivot, pdqsort)
- The same partitioning idea powers quickselect for O(n) k-th element finding
Quicksort is a masterclass in algorithm design: a simple idea (partition around a pivot) combined with careful engineering (pivot selection, partition scheme) produces the fastest general-purpose sort in practice. Its partitioning insight also underpins quickselect, one of the most useful algorithms you'll ever reach for.