Quicksort in Practice: Cutoffs, Pivots and Introsort
The quicksort of the previous lessons is the one you analyse. The quicksort in a standard library is the same idea with four engineering changes, each of which fixes a specific weakness: small subarrays are handed to insertion sort, the pivot is a median of a small sample, the recursion always goes into the smaller side first, and a depth counter switches to heapsort if the splits go badly. The result, introsort, keeps quicksort's speed and gets heapsort's worst-case guarantee. This lesson adds the changes one at a time and measures each.
1. Insertion sort for small subarrays
Most calls of quicksort are on tiny subarrays: in a recursion tree with leaves, about half the partitions handle fewer than ten elements. For those, the bookkeeping of a call (pick a pivot, set up indices, push two subproblems) costs more than the sorting. Insertion sort, which is in the worst case but has a tiny constant and is fast on nearly sorted data (Counting Steps Exactly), wins for small . So quicksort stops at subarrays of at most some cutoff size and sorts them by insertion.
import random
def quicksort(a, cutoff=1):
stats = {"comparisons": 0, "partitions": 0}
def insertion(lo, hi):
for i in range(lo + 1, hi + 1):
key, j = a[i], i - 1
while j >= lo:
stats["comparisons"] += 1
if a[j] <= key: break
a[j + 1] = a[j]; j -= 1
a[j + 1] = key
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if hi - lo + 1 <= cutoff:
insertion(lo, hi)
continue
stats["partitions"] += 1
pivot, i = a[hi], lo
for j in range(lo, hi):
stats["comparisons"] += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
stack += [(lo, i - 1), (i + 1, hi)]
return stats
rng = random.Random(1)
data = rng.sample(range(4000), 4000)
for cutoff in [1, 8, 16, 32]:
a = list(data)
s = quicksort(a, cutoff)
assert a == sorted(data)
print(f"cutoff {cutoff:>2}: {s['partitions']:>5} partitions, {s['comparisons']:>6} comparisons")cutoff 1: 2666 partitions, 54549 comparisons
cutoff 8: 798 partitions, 54924 comparisons
cutoff 16: 444 partitions, 57252 comparisons
cutoff 32: 237 partitions, 63160 comparisons
The number of comparisons barely moves for cutoffs up to about 16, while the number of partition calls drops by a factor of six. Since each partition call costs much more than one comparison in real code, the total time drops. Library sorts use cutoffs between about 16 and 32, found by measurement.
2. A better pivot: median of three
Taking the median of the first, middle and last elements as the pivot does two things. It makes sorted and reversed inputs best cases instead of worst cases (the middle element is the true median), and it makes the pivot more central on random input, which lowers the expected comparison count from to about . Larger samples (the "ninther", a median of three medians of three) are used for large arrays.
Median of three is not a guarantee: inputs exist that make it quadratic, and they can be constructed on purpose. A program that sorts data supplied by an adversary, such as a web server sorting user input, needs either a random pivot or the depth limit of step 4.
import math, random
def quicksort_count(a, rule):
c, stack = 0, [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
if rule == "median of 3" and hi - lo >= 2:
mid = (lo + hi) // 2
x, y, z = a[lo], a[mid], a[hi]
c += 2
if (x <= y) == (y <= z): m = mid # y is between x and z
else:
c += 1
m = lo if (y <= x) == (x <= z) else hi
a[m], a[hi] = a[hi], a[m]
pivot, i = a[hi], lo
for j in range(lo, hi):
c += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
stack += [(lo, i - 1), (i + 1, hi)]
assert a == sorted(a)
return c
n = 1000
rng = random.Random(1)
inputs = {"random": rng.sample(range(n), n), "sorted": list(range(n)), "reversed": list(range(n, 0, -1))}
print(f"n = {n}, n lg n = {n * math.log2(n):.0f}")
for rule in ["last element", "median of 3"]:
row = ", ".join(f"{name} {quicksort_count(list(d), rule)}" for name, d in inputs.items())
print(f"{rule:>12}: {row}")n = 1000, n lg n = 9966
last element: random 11682, sorted 499500, reversed 499500
median of 3: random 10528, sorted 8963, reversed 15631
The quadratic rows are gone. Sorted input becomes a best case, because the middle element is the exact median of every subarray; reversed input is no longer quadratic but is not ideal either, because Lomuto's partition scrambles the order of the right part; and on random input median of three saves about 10 percent even though the comparisons it spends choosing the pivot (two or three per partition) are included in the count.
3. Bounding the stack: smaller side first
Even randomized quicksort can, with bad luck, nest calls deep, and a deterministic one does so on easy inputs. Each level of recursion costs stack memory, and in languages with a fixed stack size a deep recursion crashes. The fix costs nothing: recurse into the smaller part and loop on the larger one (or, with an explicit stack, push the larger part first so the smaller one is processed next). The smaller part has at most half the elements, so the depth is at most .
def max_depth(n, smaller_first):
"""deterministic quicksort on sorted input with an explicit stack of pending subarrays.
The naive order always works on the left part first, like plain recursion does."""
a = list(range(n))
stack, deepest = [(0, n - 1)], 1
while stack:
deepest = max(deepest, len(stack))
lo, hi = stack.pop()
if lo >= hi: continue
pivot, i = a[hi], lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
left, right = (lo, i - 1), (i + 1, hi)
if smaller_first and (left[1] - left[0]) > (right[1] - right[0]):
stack += [left, right] # the smaller part is popped next
else:
stack += [right, left] # naive: the left part is popped next
return deepest
for n in [100, 400, 1600]:
print(f"n = {n:>4}: stack grows to {max_depth(n, False):>4} entries naively, {max_depth(n, True)} with smaller side first")n = 100: stack grows to 100 entries naively, 2 with smaller side first
n = 400: stack grows to 400 entries naively, 2 with smaller side first
n = 1600: stack grows to 1600 entries naively, 2 with smaller side first
On sorted input the naive order works on the big left part each time and leaves the (empty) right part pending, so one pending entry piles up per level, about in all: exactly the nested calls of the recursive version. Processing the smaller side first keeps the stack at a constant height here, and never above about in general. That bound is what makes "in place" honest for quicksort: extra memory.
4. Introsort: a depth limit with a heapsort escape
David Musser's introsort (1997) adds a counter of the recursion depth. If it exceeds about , the splits have been bad far too often, and the current subarray is finished with heapsort. Heapsort is slower than quicksort on typical data, but it is used only on the rare bad subarrays, and it caps the cost: every element is in at most partitions before it reaches heapsort or a leaf, so the total is in the worst case.
import math
def introsort_count(a, use_limit=True):
count = {"quicksort": 0, "heapsort": 0}
def heapsort(lo, hi):
n = hi - lo + 1
def sift(i, size):
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < size:
count["heapsort"] += 1
if a[lo + l] > a[lo + big]: big = l
if r < size:
count["heapsort"] += 1
if a[lo + r] > a[lo + big]: big = r
if big == i: return
a[lo + i], a[lo + big] = a[lo + big], a[lo + i]; i = big
for i in range(n // 2 - 1, -1, -1): sift(i, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]; sift(0, end)
limit = 2 * math.floor(math.log2(len(a))) if use_limit else len(a)
stack = [(0, len(a) - 1, 0)]
while stack:
lo, hi, depth = stack.pop()
if lo >= hi: continue
if depth > limit:
heapsort(lo, hi); continue
pivot, i = a[hi], lo
for j in range(lo, hi):
count["quicksort"] += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
stack += [(lo, i - 1, depth + 1), (i + 1, hi, depth + 1)]
assert a == sorted(a)
return count
n = 2000
print("plain quicksort, sorted input:", introsort_count(list(range(n)), use_limit=False))
print("introsort, sorted input:", introsort_count(list(range(n))))plain quicksort, sorted input: {'quicksort': 1999000, 'heapsort': 0}
introsort, sorted input: {'quicksort': 41769, 'heapsort': 38827}
The plain version spends its 1,999,000 comparisons. Introsort allows depths 0 to , so it makes 21 bad partitions, each removing only its pivot, then hands the remaining 1,979 elements to heapsort and finishes with about 4 percent of the work.
What the libraries do
- C++
std::sortis introsort in the major implementations: median-of-three pivots, a depth limit of with a heapsort fallback, and a final insertion-sort pass over small runs. The standard requires comparisons since C++11, which rules out plain quicksort.std::stable_sortis a merge sort. - Go (since 1.19) and Rust's
sort_unstable(in its earlier versions) use pattern-defeating quicksort (pdqsort), an introsort that also detects sorted runs and many equal keys, switching to three-way partitioning for the latter. - Java sorts primitive arrays with a dual-pivot quicksort (two pivots, three parts) and objects with Timsort, because objects need a stable sort. Python's
list.sortis a stable merge sort (Timsort), so it does not use quicksort at all.
The program counts the comparisons std::sort makes in GCC's standard library on four input shapes. All four rows stay close to : no input shape, sorted, reversed or all equal, pushes it towards a quadratic cost.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <random>
#include <vector>
int main() {
const int n = 10000;
std::vector<std::pair<const char*, std::vector<int>>> inputs;
std::vector<int> v(n);
for (int i = 0; i < n; ++i) v[i] = i;
inputs.push_back({"sorted", v});
std::reverse(v.begin(), v.end());
inputs.push_back({"reversed", v});
std::mt19937 rng(1);
for (int i = n - 1; i > 0; --i) std::swap(v[i], v[rng() % (i + 1)]);
inputs.push_back({"shuffled", v});
inputs.push_back({"all equal", std::vector<int>(n, 7)});
std::printf("n = %d, n lg n = %.0f\n", n, n * std::log2(n));
for (auto& [name, data] : inputs) {
long long count = 0;
std::sort(data.begin(), data.end(), [&count](int x, int y) { ++count; return x < y; });
std::printf("%-9s %7lld comparisons, sorted: %s\n", name, count,
std::is_sorted(data.begin(), data.end()) ? "yes" : "no");
}
}n = 10000, n lg n = 132877
sorted 166691 comparisons, sorted: yes
reversed 122058 comparisons, sorted: yes
shuffled 153573 comparisons, sorted: yes
all equal 113627 comparisons, sorted: yes
Test yourself
Why does introsort switch to heapsort when the recursion depth exceeds about ?
- Heapsort is faster than quicksort on random data
- To guarantee in the worst case while keeping quicksort's speed on typical inputs
- To make the sort stable
- To reduce memory use to
Recursing into the smaller part first (and looping on the larger) bounds the recursion depth by...
- a constant
Which statement about median-of-three pivot selection is true?
- It guarantees in the worst case
- It makes sorted inputs fast and lowers the average cost, but adversarial inputs can still make it quadratic
- It is only useful for inputs with duplicates
- It replaces the need for an insertion-sort cutoff