Sub topic 15
Selection in Linear Time: Quickselect and Median of Medians
This chapter assumes you have read the chapter on quicksort and know how partitioning around a pivot works. It also assumes you can read recurrences and solve simple ones with a recursion tree. The selection problem asks for the k-th smallest element of an unsorted list. The median is the special case k = ⌊n/2⌋. You could sort the list and index into it, which costs O(n log n). Divide and conquer can do it in O(n). Two algorithms get there. Quickselect uses a random pivot and achieves O(n) expected time. Median of medians picks its pivot deterministically and guarantees O(n) in the worst case.
From Quicksort to Quickselect
After quicksort partitions a list around a pivot, every element smaller than the pivot sits on its left and every larger element on its right. Quicksort then recurses on both sides. For selection, you already know which side holds the answer, because comparing k with the sizes of the parts tells you. That means only one recursive call is needed.
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)) # 4The three steps of the paradigm map onto this code as follows:
- Divide: partition into
lows, the copies of the pivot, andhighs. - Conquer: recurse into the one part that contains rank k. When the answer falls on the right, shift k down by the number of discarded elements.
- Combine: nothing. The recursive answer is the final answer.
Why three-way partitioning matters
The code keeps the elements equal to the pivot in their own group. Suppose you used a two-way split instead, with x <= pivot on one side. On a list where every element is equal, the left side would always be the whole list, and the recursion would never shrink. With the equal elements counted in num_pivots, every call either returns or recurses on a list that is strictly smaller, because the pivot itself is always removed. That guarantees termination.
Analyzing Quickselect
Worst case
If the pivot is the smallest or largest element every time, each call removes only one element:
T(n) = T(n − 1) + O(n) = O(n²)
With random pivots this is extremely unlikely. Still, a fixed pivot rule such as "always take the first element" makes it happen on sorted input, and an adversary who knows the rule can force it.
Expected case
Call a pivot good if its rank lies in the middle half of the list, between n/4 and 3n/4. A random pivot is good with probability 1/2, so you expect 2 partitions before you see a good one. After a good pivot, the surviving part has at most 3n/4 elements. Group the calls into phases, where a phase ends when the list shrinks below the next power of 3/4. Each phase does an expected 2 partitions of linear cost, so:
E[T(n)] ≤ 2cn · (1 + 3/4 + (3/4)² + …) = 2cn · 4 = 8cn = O(n)
The key difference from quicksort is the single recursive call. The work per level shrinks geometrically, so the sum is dominated by the first level. Quicksort does linear work at every level and pays O(n log n).
Median of Medians: A Guaranteed Good Pivot
Blum, Floyd, Pratt, Rivest, and Tarjan (1973) showed how to find a pivot that is always good enough, with no randomness:
- Split the list into groups of 5.
- Sort each group and take its median.
- Recursively select the median of those ⌈n/5⌉ medians. Call it M.
- Partition around M and recurse into one side, as in quickselect.
def mom_select(a, k):
# Deterministic k-th smallest (k starting at 0) in worst-case O(n)
if len(a) <= 5:
return sorted(a)[k]
groups = [a[i:i + 5] for i in range(0, len(a), 5)]
medians = [sorted(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)) # 50Sorting a group of 5 costs a constant, so steps 1 and 2 take O(n) together.
Why M is a good pivot
Half of the group medians are ≤ M. Each of those medians has two more elements in its group that are ≤ it. That gives at least 3 elements per group in about half the groups, roughly 3n/10 elements ≤ M. A partial last group and M's own group reduce this a little, to at least 3n/10 − 6. The symmetric argument gives at least as many elements ≥ M. So the recursive call in step 4 sees at most 7n/10 + 6 elements.
The recurrence
T(n) ≤ T(n/5) + T(7n/10 + 6) + O(n)
Here there are two recursive calls of different sizes, so the master theorem does not apply. Use a recursion tree instead. The first level does cn work. The next level works on subproblems that total n/5 + 7n/10 = 9n/10, so it does about (9/10)cn. The work shrinks by a factor of 9/10 at each level:
T(n) ≤ cn · (1 + 9/10 + (9/10)² + …) = 10cn = O(n)
The argument works because 1/5 + 7/10 < 1. The table shows how the group size affects this sum.
| Group size | Recursive sizes | Sum of fractions | Result |
|---|---|---|---|
| 3 | n/3 and 2n/3 | 1 | O(n log n) |
| 5 | n/5 and 7n/10 | 9/10 | O(n) |
| 7 | n/7 and 5n/7 | 6/7 | O(n) |
With groups of 3, the sizes add up to the full n at every level. That is the merge sort pattern, and it gives O(n log n). Any odd group size of 5 or more works.
Common Errors and Edge Cases
- Off-by-one rank. These functions use k starting at 0. If you are asked for "the 3rd smallest," pass k = 2. When you recurse into
highs, subtract bothlen(lows)andnum_pivots. - Even-length medians. For an even n, "the median" can mean the element at index n/2 − 1, the one at index n/2, or their average. Choose one on purpose.
statistics.medianreturns the average. - Memory. The list-comprehension versions allocate new lists at every level, which uses O(n) extra memory in total, because the sizes form a geometric series. An in-place version partitions a subarray
a[lo:hi]and narrows the bounds in a loop. That avoids both the copies and the recursion. - Recursion depth. Randomized quickselect has expected depth O(log n), but an unlucky run can go deeper. Since only one recursive call happens, you can turn it into a
whileloop and remove the risk of hitting Python's recursion limit. - Top-k versus k-th. After selection,
lowstogether with the pivot copies holds the k + 1 smallest elements, in no particular order. If you need them sorted, sort just those afterward: O(n + k log k).
Exercise
Explain in terms of recurrences why quickselect has expected O(n) time while quicksort has expected O(n log n) time, even though both partition around a random pivot.
Show answer
Both spend O(n) partitioning. Quicksort recurses on both sides, so with balanced splits T(n) = 2T(n/2) + O(n): every level of the recursion tree does about n work across log n levels, which gives O(n log n). Quickselect recurses on only one side, so with a good split T(n) ≤ T(3n/4) + O(n). The work per level shrinks geometrically and sums to a constant times n.
Exercise
In median of medians with groups of 7, what upper bound do you get on the size of the recursive partition call, and does the algorithm stay linear?
Show answer
Half of the n/7 group medians are ≤ M, and each brings 4 elements of its group that are ≤ it (itself and the 3 below it). That gives about 4n/14 = 2n/7 elements ≤ M, so at most about 5n/7 remain on the larger side. The recurrence becomes T(n) ≤ T(n/7) + T(5n/7) + O(n). Because 1/7 + 5/7 = 6/7 < 1, the algorithm is still O(n).
Exercise
A colleague writes quickselect with lows = [x for x in a if x <= pivot] and highs = [x for x in a if x > pivot], and recurses on lows when k < len(lows). What happens on the input [4, 4, 4, 4] with k = 1?
Show answer
Every element is ≤ 4, so lows is the whole list and highs is empty. Since k = 1 < 4, the function recurses on the same list with the same k forever, until Python raises RecursionError. Counting the pivot copies separately, as in the three-way version, guarantees that each call shrinks the list.