Quickselect & Floyd–Rivest
Expected comparisons, sampling, and selection in n + min(k, n − k) + o(n).
Quickselect finds the median with about comparisons on average, more than three times the that merely finding the minimum needs. Where does the waste come from? Mostly from pivots far from the target, which leave most elements to be compared again. Floyd and Rivest fixed that in 1975 with random sampling, reaching comparisons, which is provably optimal: for the median.
What you’ll learn
- Derive the exact expected number of comparisons of quickselect, , with indicator variables, and its entropy form .
- Explain why quickselect's cost does not concentrate, and how median-of-3 pivots, adversarial inputs and introselect change the picture.
- Describe Floyd–Rivest selection by sampling and show why it makes comparisons on average.
- State the matching lower bound of Cunto and Munro, and compare all selection methods by expected and worst-case comparisons.
The exact expected cost
Model: distinct keys, every pivot chosen uniformly at random from the current range (equivalently, a random input with any fixed pivot rule), and a partition of elements costs comparisons. Let be the number of comparisons quickselect makes to find the key of rank , counting ranks from 1.
When do two keys meet? Let be the keys in sorted order. Keys and , with , stay in the same subarray as the target until some pivot is chosen with rank between and . If that first pivot is or , the two are compared; otherwise they are separated, or the search stops at , and they never meet:
Sum over pairs by linearity of expectation. Pairs on one side of the target give simple sums; pairs that straddle it give the rest:
Evaluating the straddling sum with harmonic numbers gives Knuth's closed form, which agrees exactly with the recurrence over all pivot positions (checked with exact fractions for every ). For the minimum, , only the middle sum survives:
Asymptotics. With and , the terms cancel and an entropy remains:
Use the entropy form: about how many comparisons per element does random-pivot quickselect expect for the key of rank (the lower quartile) of a large array?
Show the answer
3.12
, so the cost is about comparisons per element: between the minimum's and the median's .
No concentration. Quicksort's cost clusters tightly around its mean, but quickselect's does not: an early bad pivot wastes a constant fraction of comparisons, and nothing later averages it out. In 20,000 simulated searches for the median with , the cost averaged with a standard deviation of about . The normalized cost converges to a random limit, not to a constant: in the same simulation, about one run in sixteen cost more than .
Better pivots, and adversaries
A pivot far from the target wastes work: most elements land on the target's side and are compared again. Taking the pivot as the median of three random elements makes central pivots likelier, and the expected cost for the median drops from to about (Kirschenhofer, Prodinger & Martínez, 1997); our simulation agrees, with the spread shrinking too, from about to . Larger samples help more, which is the road to Floyd–Rivest in the next step.
Introselect (Musser, 1997) combines speed and safety: run quickselect with cheap pivots, watch whether the range shrinks quickly enough, and switch to median-of-medians pivots if it does not. Typical inputs pay quickselect's price, and adversarial ones still finish in time. Library routines such as C++ std::nth_element, whose standard only promises linear time on average, are quickselect variants, some of them with a safeguard of this kind.
Sampling: Floyd–Rivest
Floyd and Rivest (1975) take the sampling idea to its limit. Draw a random sample, sort it, and pick two keys from it whose ranks bracket the target's expected position with a safety margin. Then one pass over the data splits it into three parts, below , between and , and above , and with high probability the target lies in the small middle part. The trick that saves comparisons: compare each element first with the bracket on the side where most elements lie.
SAMPLE-SELECT(A, k): # rank k (0-indexed), n = |A|
if n is small: sort A and return A[k]
S <- a random sample of s ≈ n^(2/3) keys; sort S # o(n) comparisons
r <- k · s / n; g <- sqrt(s · ln n) # target's place in S, and a margin
u <- S[max(0, r - g)]; v <- S[min(s - 1, r + g)]
for each x in A: # the larger side first: one comparison for most keys
if k < n / 2: test x > v (go right); otherwise test x < u (left), else middle
else: test x < u (go left); otherwise test x > v (right), else middle
continue with the part that holds rank k # with high probability the middle oneA simplified Python version of this scheme, tested against sorting, used about comparisons for the median of keys and about for : the first-order term is , but the terms fade slowly. Careful implementations recurse to choose and and tune and .
Take . Every key is compared first with . About keys exceed and are settled by that single comparison; only the roughly keys below need a second comparison, with :
Everything else is lower order. Sorting the sample costs . The middle part holds about keys. And the margin , a few standard deviations of the target's rank within the sample, makes a miss so unlikely that the expected cost of recovering from one is :
For the median that is : less than half of quickselect's , and less than the that any deterministic algorithm needs in the worst case.
Floyd–Rivest compares each key first with the bracket key on the side where most keys lie. For , about how many comparisons does the main pass make?
- About
- About
- About
- About
Show the answer
A. About
With the larger side is above , so every key is compared with first, and about keys are settled at once; only the keys below need the second comparison: .
The whole picture
| Method | Comparisons for the median | Worst case |
|---|---|---|
| Quickselect, random pivot | expected | , with tiny probability |
| Quickselect, median of 3 random keys | expected | , with tiny probability |
| Floyd–Rivest sampling | expected, optimal | not linear unless guarded |
| Introselect | as quickselect on typical inputs | |
| Median of medians | deterministic: at most (PICK) | |
| Best deterministic algorithm | at most | ; at least is necessary |
Key takeaways
- Random-pivot quickselect expects comparisons, about : for the minimum, for the median.
- Its cost does not concentrate: the standard deviation is a constant fraction of (about for the median), because early bad pivots are never averaged out.
- Better pivots help (median of 3: about ), deterministic pivot rules have adversaries, and introselect adds a linear-time fallback.
- Floyd–Rivest sampling brackets the target between two sample keys and compares each key first on the likelier side: expected comparisons, optimal by Cunto and Munro, and for the median.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
About how many comparisons does random-pivot quickselect expect to make when , finding the minimum of distinct keys?
- About
- About
- About
- About
Show the answer
B. About
The exact value is . Each round partitions the whole remaining range and keeps on average about half of it, so the ranges sum to about . A plain scan needs only , so for extreme ranks quickselect wastes about half of its work.
In the indicator-variable proof, when are the keys of ranks compared, if the target has rank ?
- Exactly when one of them is the first pivot chosen among the ranks from to
- Always: every key is compared with every pivot
- Exactly when one of them is the first pivot chosen among the ranks from to
- Exactly when both lie on the same side of
Show the answer
C. Exactly when one of them is the first pivot chosen among the ranks from to
Until a pivot lands in the range spanned by , and , all three keys stay together. The first pivot in that range compares itself with the other two if it is or , and otherwise separates them or ends the search. So the probability is .
Which statement about the spread of random-pivot quickselect's cost is true?
- Like quicksort's, it concentrates: for large almost every run costs close to the mean
- Its standard deviation grows in proportion to , so stays random even for huge
- It is deterministic once the input is fixed
- Its variance is zero for the median, by symmetry
Show the answer
B. Its standard deviation grows in proportion to , so stays random even for huge
A bad first pivot alone can waste a constant fraction of comparisons, and later rounds work on ever smaller ranges that cannot compensate. Simulations for the median show a standard deviation near , and converges to a random limit rather than to .
For the median of distinct keys, what is the least expected number of comparisons a randomized algorithm can achieve on its worst input, up to lower-order terms?
Show the answer
D.
Floyd–Rivest achieves for the median, and Cunto and Munro's average-case lower bound, transferred by Yao's principle, shows nothing does better to first order.
Further reading
- C. A. R. Hoare, "Algorithm 65: Find," Communications of the ACM 4(7) (1961), 321–322.
- R. W. Floyd & R. L. Rivest, "Expected time bounds for selection," Communications of the ACM 18(3) (1975), 165–172.
- W. Cunto & J. I. Munro, "Average case selection," Journal of the ACM 36(2) (1989), 270–279.
- P. Kirschenhofer, H. Prodinger & C. Martínez, "Analysis of Hoare's FIND algorithm with median-of-three partition," Random Structures & Algorithms 10(1–2) (1997), 143–156.
- D. R. Musser, "Introspective sorting and selection algorithms," Software: Practice and Experience 27(8) (1997), 983–993.