Sub topic 10
Introselect: Combining Speed With a Worst-Case Guarantee
This chapter assumes you already know randomized quickselect, Lomuto partitioning, and the median-of-medians algorithm from earlier chapters. It also assumes you can read Big-O arguments that sum a geometric series.
The Problem Introselect Solves
The two selection algorithms covered so far have opposite strengths:
| Algorithm | Typical speed | Worst case | Weakness |
|---|---|---|---|
| Randomized quickselect | Fast, small constants | O(n^2) | Bad pivots are unlikely, but nothing rules them out |
| Median of medians | Several times slower in practice | O(n) | Pays for the guarantee on every input |
Introselect (introspective selection), proposed by David Musser in 1997, combines the two. It runs ordinary quickselect and watches its progress. If partitioning stops shrinking the range fast enough, it switches to a fallback algorithm that has a worst-case guarantee. On normal inputs the fallback never runs, so you get quickselect's speed. On adversarial inputs the fallback caps the damage.
How the Progress Check Works
Introselect needs a cheap way to tell that quickselect is going badly. Implementations use one of two signals:
- Size check. After every few partitions, the active range should have shrunk to at most half of its size at the last checkpoint. If it has not, switch.
- Depth budget. Allow about 2·log₂(n) partitions in total. If the budget runs out, switch.
The size check is the one that gives a true O(n) bound. If the range halves every two partitions, the work is at most 2n + 2(n/2) + 2(n/4) + … ≤ 4n. If it fails to halve, you have spent at most about 2n since the last checkpoint, and the linear-time fallback adds O(n). A depth budget on its own still allows up to 2·log₂(n) partitions of nearly full size before it trips. That is O(n log n) work, which beats O(n^2) but is not linear.
An Implementation
The code below reuses the Lomuto partition and the median-of-medians function from earlier chapters so that it runs on its own. The choose_pivot parameter lets you plug in a deliberately bad strategy to watch the fallback fire.
import random
def partition(a, lo, hi, p):
"""Lomuto partition of a[lo..hi] around a[p]; returns the pivot's final index."""
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = lo
for i in range(lo, hi):
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store]
return store
def select_mom(items, k):
"""Deterministic worst-case O(n) selection (0-based k) using median of medians."""
if len(items) <= 5:
return sorted(items)[k]
chunks = [items[i:i + 5] for i in range(0, len(items), 5)]
medians = [sorted(c)[len(c) // 2] for c in chunks]
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))
fallbacks = 0 # counts how often the safety net was used
def introselect(a, k, choose_pivot=random.randint):
"""Return the k-th smallest element (0-based), reordering a in place."""
global fallbacks
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
checkpoint, steps = len(a), 0
while lo < hi:
if steps == 2:
size = hi - lo + 1
if size > checkpoint // 2:
fallbacks += 1
return select_mom(a[lo:hi + 1], k - lo)
checkpoint, steps = size, 0
p = partition(a, lo, hi, choose_pivot(lo, hi))
steps += 1
if k == p:
return a[k]
elif k < p:
hi = p - 1
else:
lo = p + 1
return a[k]
def first_element(lo, hi):
return lo
data = list(range(2000))
print(introselect(data[:], 1000)) # 1000
print(introselect(data[:], 1000, choose_pivot=first_element)) # 1000
print("fallbacks:", fallbacks) # fallbacks: 1With a random pivot the first call almost never trips the check. The second call uses the first element as the pivot on sorted input, which is the classic O(n^2) case. Each partition removes only one element, so after two steps the range is still 1998 elements and introselect hands off to median of medians.
Choosing the Fallback
| Fallback | Worst case of the whole algorithm | Used by |
|---|---|---|
| Median of medians + size check | O(n) | Musser's original proposal; Rust's `select_nth_unstable` documents an O(n) worst case |
| Heapselect + depth budget | O(n log n) | GCC's libstdc++ `std::nth_element` |
| None (plain quickselect) | O(n^2) | Simple hand-written code |
Heapselect is popular because it is simple, works in place, and has small constants. The fallback is reached so rarely that its asymptotic cost matters less than code size and predictability.
Exercise
Why does introselect check whether the range has halved after every two partitions instead of after every single partition?
Show answer
With a random or median-of-three pivot, a single partition often removes less than half of the range just by bad luck, so checking every step would trigger the slow fallback far too often. Allowing two steps per halving still bounds the work by a geometric series of about 4n, so the O(n) guarantee survives, and false alarms become rare.
Exercise
An implementation allows 2·log₂(n) partitions and then switches to median of medians. Why is its worst case O(n log n) and not O(n)?
Show answer
An adversary can make each of the 2·log₂(n) partitions remove only a constant number of elements. Each one then costs about n comparisons, which totals Θ(n log n) before the fallback starts. The linear fallback cannot recover that work. Only a check on how fast the range shrinks forces the geometric decrease that the linear bound needs.