Sub topic 15
Selection in Linear Time: Quickselect and Median of Medians
This chapter assumes you know quicksort's partition step, Big-O notation, and how to read recurrences. The selection problem asks for the k-th smallest element of an unsorted list. Sorting the list first solves it in O(n log n) time. Divide and conquer can do it in O(n).
From Quicksort to Quickselect
Quicksort partitions the list around a pivot and then recurses on both sides. For selection, only one side can contain the answer. After partitioning, you know how many elements are smaller than the pivot, so you know which side the k-th smallest element is on. You recurse into that side and ignore the other.
import random
def quickselect(a, k):
# Returns the k-th smallest element of a non-empty list, with k starting at 0
pivot = random.choice(a)
lows = [x for x in a if x < pivot]
highs = [x for x in a if x > pivot]
num_pivots = len(a) - len(lows) - len(highs)
if k < len(lows):
return quickselect(lows, k)
if k < len(lows) + num_pivots:
return pivot
return quickselect(highs, k - len(lows) - num_pivots)
print(quickselect([7, 2, 9, 4, 1, 8], 2)) # 4Why Expected Time Is Linear
A random pivot lands in the middle half of the list with probability 1/2. When that happens, the next call gets at most 3n/4 elements. Partitioning costs O(n), so the expected work forms a geometric series: n + (3/4)n + (9/16)n + ... = O(n).
The worst case is still O(n²). If the pivot is always the minimum or maximum, each call removes only one element, which gives T(n) = T(n − 1) + O(n).
Median of Medians: A Guaranteed Good Pivot
To make the worst case linear, choose the pivot deterministically:
- Split the list into groups of 5 and find the median of each group.
- Recursively select the median of those n/5 medians.
- Use it as the pivot.
Half of the group medians are at least as large as the pivot. Each of those medians has two more elements in its group that are at least as large as itself. So roughly 3n/10 elements are at least the pivot, and by the same argument roughly 3n/10 are at most the pivot. Either side therefore holds at most about 7n/10 elements.
def mom_select(a, k):
if len(a) <= 5:
return sorted(a)[k]
groups = [sorted(a[i:i + 5]) for i in range(0, len(a), 5)]
medians = [g[len(g) // 2] for g in groups]
pivot = mom_select(medians, len(medians) // 2)
lows = [x for x in a if x < pivot]
highs = [x for x in a if x > pivot]
num_pivots = len(a) - len(lows) - len(highs)
if k < len(lows):
return mom_select(lows, k)
if k < len(lows) + num_pivots:
return pivot
return mom_select(highs, k - len(lows) - num_pivots)
print(mom_select(list(range(100, 0, -1)), 49)) # 50The recurrence is T(n) ≤ T(n/5) + T(7n/10) + O(n). The master theorem does not cover recurrences with two unequal subproblems like this, so use a recursion tree. Each level does at most 9/10 of the work of the level above it, because 1/5 + 7/10 = 9/10 < 1. The levels form a decreasing geometric series, so T(n) = O(n).
| Method | Expected time | Worst case | Constant factor |
|---|---|---|---|
| Sort then index | O(n log n) | O(n log n) | Low |
| Quickselect | O(n) | O(n²) | Low |
| Median of medians | O(n) | O(n) | High |
In practice, libraries usually run quickselect and switch to median of medians only when the recursion goes badly. This hybrid is called introselect.
Exercise
Suppose median of medians used groups of 3 instead of 5. The pivot then leaves at most about 2n/3 elements on either side. Write the recurrence and say whether it is still linear.
Show answer
T(n) = T(n/3) + T(2n/3) + O(n). The fractions sum to exactly 1, so each level of the recursion tree does about n work across roughly log n levels. The total is O(n log n), so groups of 3 are not linear.
Exercise
Why does quickselect run in expected O(n) time while quicksort needs O(n log n)?
Show answer
Quickselect recurses into only one side of the partition, so the subproblem sizes shrink geometrically and sum to O(n). Quicksort recurses into both sides, so each level of recursion still does O(n) total work across about log n levels.