Sub topic 6
Why Quickselect Is Expected O(n) but Worst-Case O(n^2)
This chapter assumes you know Big-O notation and geometric series, and that you have seen the Lomuto partition function and the iterative quickselect loop from earlier chapters. The goal is to explain why quickselect is usually fast, and what makes it slow on some inputs.
The cost model
Each round of quickselect does two things:
- It partitions the current subarray
a[lo..hi], which takeshi - locomparisons. That cost is linear in the subarray's size. - It keeps only the side that contains index
kand throws the rest away.
The total running time is the sum of the sizes of all the subarrays that get partitioned. Everything depends on how fast those sizes shrink.
The ideal case: halving
Suppose every pivot lands exactly in the middle. The sizes are then n, n/2, n/4, and so on, and the total work is a geometric series:
n + n/2 + n/4 + ... < 2n
This is the key difference from quicksort. Quicksort recurses into both halves, so every level of recursion costs about n and there are log n levels. Quickselect keeps one half per level, so each level costs half as much as the one before.
The worst case: shrinking by one
Now suppose every pivot is the smallest (or largest) element of its subarray. Each partition then removes only the pivot, and the sizes are n, n−1, n−2, and so on:
n + (n−1) + (n−2) + ... + 1 = n(n+1)/2 = O(n²)
The area under each line is the total work. The balanced line's area stops growing almost at once. The extreme line's area grows roughly quadratically.
Why a random pivot gives expected O(n)
Pivots don't need to be perfect. They only need to be "good enough" a reasonable fraction of the time. Call a pivot good if its rank falls in the middle half of the subarray, between the 25th and 75th percentiles. Then:
- A uniformly random pivot is good with probability 1/2.
- A good pivot leaves at most 3/4 of the subarray, whichever side holds
k.
Group the rounds into phases. Phase j lasts while the subarray size is between n(3/4)^(j+1) and n(3/4)^j. One good pivot ends a phase, and you expect a good pivot within 2 tries. So each phase has an expected 2 partitions, and each of those costs at most n(3/4)^j:
Expected total ≤ Σ 2 · n(3/4)^j = 2n · 4 = 8n = O(n)
The constant 8 is loose. A tighter analysis puts finding the median at about 3.4n comparisons. The randomness comes from the algorithm, not from the input. No input is bad for random pivots. Only an unlucky run of coin flips is, and the chance of a long unlucky run drops exponentially with its length.
What triggers the worst case in practice
| Situation | Why it degrades |
|---|---|
| First or last element as pivot, input already sorted or reverse sorted | Each pivot is the min or max of its subarray |
| Two-way partitioning on many equal keys | All equal elements fall on one side, so the split stays lopsided |
| A deterministic pivot rule and inputs chosen by an attacker | An adversary can construct inputs that defeat any fixed rule |
The second row is the subject of the three-way partitioning chapter. The third row is why libraries add a fallback with a guaranteed bound, which later chapters cover.
Measuring it
The script below counts comparisons with a first-element pivot and with a random pivot on sorted input.
import random
def count_comparisons(items, k, choose):
"""Run iterative Lomuto quickselect and return the number of comparisons."""
a = list(items)
comps = 0
lo, hi = 0, len(a) - 1
while lo < hi:
p = choose(lo, hi)
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = lo
for i in range(lo, hi):
comps += 1
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store]
if k == store:
break
elif k < store:
hi = store - 1
else:
lo = store + 1
return comps
n = 4000
data = list(range(n)) # already sorted
k = n // 2 # the median
first = count_comparisons(data, k, lambda lo, hi: lo)
rand = count_comparisons(data, k, lambda lo, hi: random.randint(lo, hi))
print(f"first-element pivot: {first:>9} comparisons ({first / n:.1f} per element)")
print(f"random pivot: {rand:>9} comparisons ({rand / n:.1f} per element)")With the first-element pivot, the count is about 6 million, roughly 1500 per element. With the random pivot it is usually around 3 to 4 per element. Double n and the first number roughly quadruples, while the second roughly doubles.
Exercise
Suppose every pivot leaves at most 9/10 of the subarray, a very lopsided but consistent split. Is quickselect still O(n)? Give the bound.
Show answer
Yes. The sizes are at most n, 0.9n, 0.81n, and so on, so the total is at most n · 1/(1 − 0.9) = 10n, which is O(n). Any fixed fraction below 1 gives linear time. Only splits that remove a constant number of elements per round, rather than a constant fraction, lead to O(n²).
Exercise
Why does quicksort with perfect pivots take O(n log n) while quickselect with perfect pivots takes O(n)?
Show answer
Quicksort recurses into both sides, so each level of recursion processes about n elements in total, across log n levels. Quickselect recurses into one side, so the work per level halves and sums to less than 2n.