Sub topic 6
Why Quickselect Is Expected O(n) but Worst-Case O(n^2)
This chapter assumes you can read Big-O notation, follow a short induction argument, and recognize the Lomuto partition and the iterative quickselect loop from earlier chapters. You do not need probability theory beyond the idea of an average, or "expected value."
The goal is to explain where quickselect's running time comes from. You will see why one bad pivot costs almost nothing, why a long run of bad pivots costs a lot, and why randomization makes a long run of bad pivots unlikely on every input.
The Cost Model: Count Comparisons Per Partition
Quickselect does nearly all of its work inside partition. A Lomuto partition of a subarray with m elements compares each of the other m - 1 elements with the pivot exactly once. Swaps and index updates are bounded by the number of comparisons, so the comparison count is a fair measure of total work.
The whole run is therefore a sum:
- Round 1 partitions all
nelements:n - 1comparisons. - Round 2 partitions the surviving side, of size
m2:m2 - 1comparisons. - This continues until the pivot lands on index
kor the subarray has one element.
The running time depends entirely on how fast the subarray shrinks. The pivot decides that.
The Recurrence
Suppose the pivot ends up at position i within a subarray of size n. The left side has i elements and the right side has n - 1 - i. Quickselect keeps only one side, and in the worst situation it keeps the larger one. That gives the recurrence:
T(n) = (n - 1) + T(max(i, n - 1 - i))Quicksort's recurrence has the same partition cost but recurses into both sides:
T_sort(n) = (n - 1) + T_sort(i) + T_sort(n - 1 - i)The two sides of quicksort together still contain n - 1 elements, so every level of quicksort's recursion tree costs about n, and there are about log n levels. Quickselect's levels get smaller as it goes, so their costs add up like a shrinking series. That difference is why quicksort is O(n log n) and quickselect is O(n).
Best Case: A Geometric Series
If every pivot lands exactly in the middle, each subarray is half the size of the previous one:
n + n/2 + n/4 + n/8 + ... < 2nThis is a geometric series with ratio 1/2, and its sum is bounded by 2n no matter how many terms it has. The useful point is that the ratio does not need to be 1/2. Any fixed fraction below 1 gives a linear bound:
| Fraction kept each round | Sum of the series | Bound |
|---|---|---|
| 1/2 | n / (1 - 1/2) | 2n |
| 3/4 | n / (1 - 3/4) | 4n |
| 9/10 | n / (1 - 9/10) | 10n |
| 99/100 | n / (1 - 99/100) | 100n |
Even a pivot that only ever cuts off 1% of the array gives O(n), with a bad constant. The real danger is a pivot that cuts off a constant number of elements instead of a constant fraction.
Worst Case: An Arithmetic Series
If every pivot is the smallest or largest element of its subarray, each round removes only the pivot:
(n - 1) + (n - 2) + (n - 3) + ... + 1 = n(n - 1) / 2That is an arithmetic series, and it grows as O(n^2). For n = 1,000,000, it means about 5 × 10^11 comparisons where the good case needs a few million.
Why Random Pivots Give Expected O(n)
A random pivot is not guaranteed to be good, but it is good often enough. You can see this with a short argument that avoids heavy algebra.
Good Pivots and Phases
Call a pivot good if it lands in the middle half of the subarray, between the 25th and 75th percentile. After a good pivot, the side that survives has at most 3/4 of the elements. A uniformly random pivot is good with probability 1/2, because half of the positions lie in the middle half.
Group the rounds into phases. A phase ends at the first good pivot. Two facts follow:
- Each round in a phase partitions at most the size the subarray had when the phase started, since subarrays only shrink.
- The number of rounds until the first good pivot behaves like flipping a fair coin until it lands heads, so a phase lasts 2 rounds on average.
Phase j starts with at most (3/4)^j · n elements, so its expected cost is at most 2 · (3/4)^j · n. Summing over all phases:
E[comparisons] ≤ 2n · (1 + 3/4 + (3/4)^2 + ...) = 2n · 4 = 8nThe bound of 8n is loose, but it is linear, and that is the point.
A Tighter Bound by Induction
You can also bound the recurrence directly. Assume the worst case each round, where the larger side survives. With a random pivot, the larger side has size i for each i from about n/2 to n - 1, and each of those sizes occurs with probability about 2/n:
E[T(n)] ≤ (n - 1) + (2/n) · Σ_{i = n/2}^{n-1} E[T(i)]Suppose E[T(i)] ≤ c·i for all smaller i. The sum of i from n/2 to n - 1 is about 3n²/8, so:
E[T(n)] ≤ n + (2/n) · c · (3n²/8) = n + (3c/4) · nThis is at most c·n whenever c ≥ 4, which gives E[T(n)] ≤ 4n. A more careful analysis gives the exact expected comparison count. It is largest when k is the median, at about 2(1 + ln 2) · n ≈ 3.39n, and it falls toward 2n when k is near either end.
How Likely Is a Slow Run?
The expected value alone does not rule out an occasional slow run. Slow runs need many bad pivots in a row, and each bad pivot happens with probability at most 1/2, independently of the others. The probability of the running time exceeding a large multiple of n therefore drops exponentially in that multiple. In practice, randomized quickselect on a million elements almost always finishes within a small constant factor of 3.4n comparisons.
Measuring It
The script below counts comparisons for three situations: a random pivot on shuffled data, a first-element pivot on sorted data, and a random pivot on an array where every value is equal.
import random
def partition_count(a, lo, hi, p):
"""Lomuto partition of a[lo..hi] around a[p]; returns (pivot index, comparisons)."""
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = lo
comps = 0
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]
return store, comps
def quickselect_count(a, k, choose):
"""Iterative quickselect that returns (k-th smallest, total comparisons)."""
lo, hi = 0, len(a) - 1
total = 0
while lo < hi:
p, c = partition_count(a, lo, hi, choose(lo, hi))
total += c
if k == p:
break
elif k < p:
hi = p - 1
else:
lo = p + 1
return a[k], total
def first(lo, hi):
return lo
def rand(lo, hi):
return random.randint(lo, hi)
n = 2000
data = list(range(n))
random.shuffle(data)
value, comps = quickselect_count(data, n // 2, rand)
print("random pivot, shuffled, median:", value, comps, round(comps / n, 2), "x n")
value, comps = quickselect_count(list(range(n)), n - 1, first)
print("first pivot, sorted, max: ", value, comps)
value, comps = quickselect_count([7] * n, n - 1, rand)
print("random pivot, all equal, max: ", value, comps)
print("n(n-1)/2 =", n * (n - 1) // 2)The first line changes from run to run, but the ratio usually lands between about 2 and 5 times n, centered near 3.4. The other two lines always print 1999000, which equals n(n - 1)/2.
The sorted-input case is quadratic because the first element of a sorted subarray is always its minimum. In this Lomuto implementation the subarray even stays sorted after each partition, so every round makes the same bad choice.
The all-equal case is more surprising. The pivot is random, yet the run is still quadratic.
What Actually Triggers O(n^2)
Randomization protects against bad pivot positions, but it cannot help when every position is bad. The common causes are listed below.
| Trigger | Why each round removes only about one element | Fix |
|---|---|---|
| First or last element as pivot on sorted or reversed input | The pivot is always the min or max | Random pivot (see the pivot selection chapter) |
| Deterministic median-of-three on crafted input | An attacker can build "killer" sequences that defeat a fixed rule | Random pivot, or a worst-case fallback |
| Many equal keys with two-way partitioning | `a[i] < pivot` is false for all equal elements, so they all land on one side | Three-way partitioning (next chapter) |
| Extremely unlucky random choices | Every pivot happens to be near an end | Probability shrinks exponentially; ignore in practice, or add a fallback |
The duplicate case deserves attention because it defeats the guarantee from the previous section. That analysis assumed distinct keys, so that a random pivot's final position was uniformly random. With all keys equal, Lomuto places every pivot at lo, whichever element you pick. Inputs with only a few distinct values, such as ratings from 1 to 5 or boolean flags, behave nearly as badly.
Space and Recursion Depth
The time analysis also controls stack usage. A recursive quickselect makes one recursive call per round, so its depth equals the number of rounds. That is O(log n) expected but n - 1 in the worst case. Python's default recursion limit is about 1000, so a recursive version raises RecursionError on the sorted-input example above long before the quadratic time becomes noticeable.
The iterative loop from the earlier chapter uses O(1) extra space in every case. Switching to it fixes the crash, but it does not fix the quadratic time. These are separate problems with separate fixes.
The list-building version, quickselect_simple, allocates new lists each round. Its extra memory follows the same series as its time: about 2n total allocation in the good case, and O(n^2) total allocation in the bad case, although at most O(n) is live at once if earlier lists are freed.
Summary of the Bounds
| Case | Subarray sizes | Comparisons | Order |
|---|---|---|---|
| Best (pivot lands on k at once) | n | n - 1 | O(n) |
| Perfect halving | n, n/2, n/4, ... | under 2n | O(n) |
| Random pivot, distinct keys, k = median | shrinks by a random fraction | about 3.39n expected | O(n) expected |
| Pivot always at an end | n, n-1, n-2, ... | n(n-1)/2 | O(n^2) |
A worst-case O(n) bound needs a pivot rule that always discards a constant fraction of the elements, every round, without luck. Median of medians, covered in a later chapter, provides exactly that.
Exercise
A pivot rule always leaves at most 9/10 of the subarray after each partition, on every input. Give an upper bound on total comparisons and its Big-O class.
Show answer
The sizes are at most n, (9/10)n, (9/10)^2 n, ..., so the comparisons are at most n / (1 - 9/10) = 10n. That is worst-case O(n). Any fixed fraction below 1 gives a linear bound; only the constant changes.
Exercise
Using the Lomuto partition from this chapter with a random pivot, how many comparisons does quickselect make to find k = 0 in an array of n equal values? Compare it with k = n - 1.
Show answer
For k = 0, the first partition puts the pivot at index lo = 0, which equals k, so the loop stops after n - 1 comparisons. For k = n - 1, every partition places the pivot at lo, lo increases by one each round, and the total is n(n - 1)/2. The duplicate problem appears only when k lies away from the side where Lomuto piles up the equal keys.
Exercise
Why does the expected-time bound of randomized quickselect hold for sorted input, while the bound for a "random input, first-element pivot" analysis does not protect you from sorted input?
Show answer
With a random pivot, the expectation is taken over the algorithm's own coin flips, so the bound holds for every fixed input, including sorted ones. With a first-element pivot, any average-case bound is over a distribution of inputs. Sorted input is a single specific input outside that average, and it makes every pivot the minimum, which gives n(n - 1)/2 comparisons.