Sub topic 10
Introselect: Combining Speed With a Worst-Case Guarantee
This chapter assumes you have read the earlier chapters on Lomuto and three-way partitioning, randomized quickselect, pivot strategies, and median of medians. You should be comfortable with Big-O notation and with the argument that a pivot discarding a constant fraction of the input gives linear total work.
The earlier chapters left you with two algorithms. Quickselect with a cheap pivot is fast on almost every input, but some inputs push it to O(n^2). Median of medians always finishes in O(n), but its constant factors make it several times slower than quickselect on typical data. Introselect combines the two. It runs quickselect normally, watches how fast the range is shrinking, and switches to a guaranteed pivot only when progress stalls.
The Problem Introselect Solves
The cost of quickselect depends on how much each partition shrinks the active range. A good pivot roughly halves the range, so the total work is about n + n/2 + n/4 + ..., which is under 2n. A bad pivot removes only one element, so the total becomes n + (n−1) + (n−2) + ..., which is quadratic.
Randomizing the pivot makes the bad case very unlikely, but it has three costs:
- Determinism. Some systems need repeatable behavior, for example reproducible builds, deterministic tests, or consensus code. A random pivot makes run time vary between runs.
- Adversaries. A cheap deterministic rule such as median-of-three can be attacked. Someone who knows your pivot rule can craft input that makes every pivot poor. This is a real denial-of-service risk when the input comes from users.
- Guarantees. "Expected O(n)" is a statement about averages. Some contracts, such as real-time budgets or library specifications, need a bound that holds for every input.
Median of medians solves all three but pays for it on every call. Introselect, introduced by David Musser in 1997 together with introsort, pays the extra cost only on inputs that need it.
How Introselect Works
The algorithm has two modes:
- Fast mode. Pick the pivot with a cheap rule (median-of-three or random), partition, and keep the side that contains index k. This is ordinary quickselect.
- Safe mode. Pick the pivot with median of medians, which guarantees that a constant fraction of the range is discarded.
A progress monitor decides when to leave fast mode. As long as the range shrinks fast enough, the algorithm stays in fast mode. When the monitor sees too little progress, it switches to safe mode for the rest of the call. A small-range cutoff then finishes the last few elements with a simple sort.
Choosing the Progress Trigger
The trigger is the main design decision. Three common rules are compared below.
| Trigger | Rule | Worst-case work before switching | Guarantee it supports |
|---|---|---|---|
| Depth limit | Switch after about 2·log2(n) partitions | O(n log n) | O(n log n) overall, or O(n) only with a further argument |
| Halving check | Every two partitions, the range must have at least halved | At most about 4n | O(n) overall |
| Work budget | Switch when the total partitioned length exceeds c·n | At most c·n | O(n) overall |
A depth limit is the simplest rule and the one introsort uses. For selection it is weaker than it looks. Each of the 2·log2(n) bad partitions can still cost close to n, so fast mode alone can spend O(n log n) before the switch happens.
The halving check, which Musser proposed for introselect, bounds fast-mode work directly. If the range halves every two steps, fast-mode work is at most n + n + n/2 + n/2 + n/4 + n/4 + ..., which is about 4n. As soon as one pair of steps fails to halve the range, the algorithm switches, and median of medians finishes in linear time. Each mode costs O(n), so the whole call is O(n).
A work budget is equivalent in spirit. It is easier to tune but needs a running counter.
A Python Implementation
The code below uses three-way partitioning, so duplicate keys cannot cause stalls. Median-of-three is the fast pivot, median of medians is the safe pivot, and a halving check is the trigger. The fast pivot is a parameter so that you can plug in a deliberately bad rule and watch the guard work.
def _partition3(a, lo, hi, pivot):
"""Three-way partition a[lo..hi] around a pivot value.
Afterwards a[lo:lt] < pivot, a[lt:gt+1] == pivot, a[gt+1:hi+1] > pivot.
Returns (lt, gt).
"""
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
return lt, gt
def _select_mom(items, k):
"""Deterministic O(n) selection on a list (0-based k)."""
if len(items) <= 5:
return sorted(items)[k]
medians = [sorted(items[i:i + 5])[len(items[i:i + 5]) // 2]
for i in range(0, len(items), 5)]
pivot = _select_mom(medians, len(medians) // 2)
lows = [x for x in items if x < pivot]
pivots = [x for x in items if x == pivot]
highs = [x for x in items if x > pivot]
if k < len(lows):
return _select_mom(lows, k)
if k < len(lows) + len(pivots):
return pivot
return _select_mom(highs, k - len(lows) - len(pivots))
def mom_pivot(a, lo, hi):
"""Median-of-medians pivot value for a[lo..hi]."""
medians = []
for i in range(lo, hi + 1, 5):
group = sorted(a[i:min(i + 5, hi + 1)])
medians.append(group[len(group) // 2])
return _select_mom(medians, len(medians) // 2)
def median_of_three(a, lo, hi):
"""Cheap pivot value: median of the first, middle, and last elements."""
mid = (lo + hi) // 2
return sorted((a[lo], a[mid], a[hi]))[1]
def first_element(a, lo, hi):
"""A deliberately weak pivot rule, used only to exercise the guard."""
return a[lo]
CUTOFF = 16
def introselect(a, k, fast_pivot=median_of_three, stats=None):
"""Return the k-th smallest element (0-based) of list a, reordering a in place.
Worst-case O(n): fast mode is abandoned as soon as the range fails to
halve over two consecutive partitions.
"""
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
safe_mode = False
steps = 0
checkpoint = hi - lo + 1
while hi - lo + 1 > CUTOFF:
if stats is not None:
stats["work"] += hi - lo + 1
pivot = mom_pivot(a, lo, hi) if safe_mode else fast_pivot(a, lo, hi)
lt, gt = _partition3(a, lo, hi, pivot)
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
if not safe_mode:
steps += 1
if steps == 2:
size = hi - lo + 1
if size > checkpoint // 2:
safe_mode = True
if stats is not None:
stats["switched"] = True
checkpoint = size
steps = 0
a[lo:hi + 1] = sorted(a[lo:hi + 1])
return a[k]
print(introselect([9, 1, 8, 2, 7, 3], 2)) # 3
n = 20000
data = list(range(n))
s = {"work": 0, "switched": False}
print(introselect(data[:], n // 2, fast_pivot=first_element, stats=s)) # 10000
print(s["switched"]) # True
print(s["work"] / n < 10) # TrueOn sorted input, first_element is the worst possible rule: each partition removes one element. Plain quickselect with that rule would touch roughly 0.375·n^2 elements here, about 150 million. Introselect notices after two partitions that the range has not halved, switches to median of medians, and finishes after a few multiples of n.
Invariants worth checking
- k stays in range. Every narrowing step keeps
lo <= k <= hi, because the code moves only the boundary on the side that does not contain k. Three-way partitioning also guarantees that the equal block is non-empty, since the pivot value always occurs in the range, so the range strictly shrinks. - Safe mode is permanent. Once the algorithm switches, it never switches back. Switching back would let an adversary alternate between modes and defeat the bound.
- The checkpoint resets after every check. The halving test compares against the size measured two steps earlier, not against the original n. Comparing against n would let fast mode run for many steps after the range had stopped shrinking.
Choosing the Fallback
Median of medians is not the only possible fallback, and real libraries differ on this choice.
| Fallback | Worst case after switching | Extra memory | Notes |
|---|---|---|---|
| Median of medians | O(n) | O(1) in place, O(log n) recursion | The only fallback here that gives true worst-case linear time |
| Heapselect | O(n log k) or O(n log n) | O(1) | Simple and in place. GCC's libstdc++ `nth_element` uses it |
| Full sort of the range | O(n log n) | Depends on the sort | Easiest to write. Fine when a log factor is acceptable |
| Switch to random pivots | Expected O(n), no hard bound | O(1) | Defeats fixed attacks but keeps quadratic tails |
GCC's libstdc++ implements std::nth_element as introselect. It uses median-of-three pivots, a depth limit of 2·log2(n), and heapselect as the fallback. That combination bounds the worst case at O(n log n), not O(n). The C++ standard only requires nth_element to run in linear time on average, so the choice is conforming. If you need a strict linear bound, check what your library actually promises before relying on it. The next chapter covers the library routines in detail.
Failure Modes and Gotchas
A guard that never fires
If the trigger compares against the wrong baseline, or the step counter is never reset, fast mode can run indefinitely on bad input. Test the guard directly. Inject a weak pivot rule such as first_element, run it on sorted input, and assert that the switch happens and that total work stays within a constant multiple of n. The demo above does exactly this.
A guard that fires too often
A strict trigger, for example "every single step must halve the range", fires on ordinary unlucky pivots. Each false alarm moves a benign input into the slow mode. Checking over two steps, or with a budget such as 3n to 4n, tolerates normal variation while still catching sustained bad luck.
Duplicate keys
Introselect built on Lomuto or two-way partitioning can still stall when many keys are equal. The guard would catch this and switch modes, but median of medians with two-way partitioning also handles duplicates badly. Three-way partitioning fixes the problem at its source, so use it in both modes.
Cutoff size
The small-range cutoff (16 here) avoids running partition and pivot logic on tiny ranges, where insertion sort or a direct sort is faster. Its value affects speed only, not correctness. Production code usually picks a value between 8 and 32 after benchmarking.
Determinism versus randomness
With median-of-three as the fast rule, the whole algorithm is deterministic. The same input always produces the same result and the same running time, and adversarial input still costs O(n). With a random fast pivot, the guard almost never fires, but running time varies from run to run. Both choices are valid. Pick the one that matches your need for reproducibility.
When to Reach for Introselect
Use introselect, or a library routine built on it, when any of these apply:
- The input may be controlled by an adversary, such as request payloads or uploaded data.
- You need a deterministic algorithm with a predictable upper bound.
- You want quickselect's typical speed without accepting a quadratic tail.
Plain randomized quickselect is enough for trusted data where the expected running time is all you care about. Median of medians on its own is rarely the right choice in practice, because introselect gives the same guarantee and usually runs about as fast as quickselect.
Exercise
Why does a depth limit of 2·log2(n) partitions guarantee only O(n log n) for selection, while a "range must halve every two steps" rule guarantees O(n)?
Show answer
With a depth limit, each of the up to 2·log2(n) fast-mode partitions can scan nearly the whole range, for example when every pivot removes one element, so fast mode alone can cost about 2·n·log2(n). The halving rule bounds the total size of the scanned ranges directly: fast-mode work is at most n + n + n/2 + n/2 + ..., which is about 4n. After the switch, median of medians adds O(n), so the total is O(n).
Exercise
In the implementation, suppose you change the halving test to if size > n // 2: where n is the original length. What goes wrong?
Show answer
The test then checks only whether the range has fallen below half of the original input. Once the range drops below n/2 the guard can never fire again, even if every later pivot removes only one element. Fast mode could then cost about (n/2)^2 / 2, which is quadratic. The baseline must be the size from the previous checkpoint.
Exercise
You run introselect with random fast pivots on a list of one million equal integers. Using two-way Lomuto partitioning, what happens, and how does three-way partitioning change it?
Show answer
With Lomuto, every element equals the pivot, so each partition places the pivot at one end and removes a single element. The halving guard fires after two steps and switches to median of medians, but median of medians with two-way partitioning has the same problem, so progress stays slow. With three-way partitioning, the first partition puts every element in the equal block, k falls inside it, and the call returns after one linear pass.