Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Quickselect & Floyd–Rivest

Expected comparisons, sampling, and selection in n + min(k, n − k) + o(n).

Quickselect finds the median with about 3.39n3.39n comparisons on average, more than three times the n−1n - 1 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 n+min⁡(k,n−k)+o(n)n + \min(k, n-k) + o(n) comparisons, which is provably optimal: 1.5n1.5n for the median.

What you’ll learn

  • Derive the exact expected number of comparisons of quickselect, 2[(n+1)Hn−(n+3−k)Hn+1−k−(k+2)Hk+n+3]2[(n+1)H_n - (n+3-k)H_{n+1-k} - (k+2)H_k + n + 3], with indicator variables, and its entropy form 2n(1+h(k/n))2n(1 + h(k/n)).
  • 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 n+min⁡(k,n−k)+o(n)n + \min(k, n - k) + o(n) 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: nn 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 mm elements costs m−1m - 1 comparisons. Let C(n,k)C(n, k) be the number of comparisons quickselect makes to find the key of rank kk, counting ranks from 1.

DerivationProof with indicator variables
  1. Pr⁡[zi and zj are compared]=2max⁡(j,k)−min⁡(i,k)+1\Pr[z_i \text{ and } z_j \text{ are compared}] = \frac{2}{\max(j, k) - \min(i, k) + 1}

    When do two keys meet? Let z1<⋯<znz_1 < \dots < z_n be the keys in sorted order. Keys ziz_i and zjz_j, with i<ji < j, stay in the same subarray as the target zkz_k until some pivot is chosen with rank between min⁡(i,k)\min(i, k) and max⁡(j,k)\max(j, k). If that first pivot is ziz_i or zjz_j, the two are compared; otherwise they are separated, or the search stops at zkz_k, and they never meet:

  2. E[C]=∑i<j≤k2k−i+1⏟2(k−Hk)+∑k≤i<j2j−k+1⏟2(n−k+1−Hn−k+1)+∑i<k<j2j−i+1\E[C] = \underbrace{\sum_{i < j \le k} \frac{2}{k - i + 1}}_{2(k - H_k)} + \underbrace{\sum_{k \le i < j} \frac{2}{j - k + 1}}_{2(n - k + 1 - H_{n-k+1})} + \sum_{i < k < j} \frac{2}{j - i + 1}

    Sum over pairs by linearity of expectation. Pairs on one side of the target give simple sums; pairs that straddle it give the rest:

  3. E[C(n,1)]=2(n−Hn)≈2n\E[C(n, 1)] = 2(n - H_n) \approx 2n

    Evaluating the straddling sum with harmonic numbers gives Knuth's closed form, which agrees exactly with the recurrence C(n,k)=n−1+1n∑p(⋯ )C(n, k) = n - 1 + \tfrac1n \sum_p (\cdots) over all pivot positions (checked with exact fractions for every k≤n≤60k \le n \le 60). For the minimum, k=1k = 1, only the middle sum survives:

  4. E[C(n,αn)]=2n(1+h(α))+O(log⁡n),2(1+h(12))=2(1+ln⁡2)≈3.386\E[C(n, \alpha n)] = 2n\big(1 + h(\alpha)\big) + O(\log n), \qquad 2\big(1 + h(\tfrac12)\big) = 2(1 + \ln 2) \approx 3.386

    Asymptotics. With Hm=ln⁡m+γ+O(1/m)H_m = \ln m + \gamma + O(1/m) and k=αnk = \alpha n, the nln⁡nn \ln n terms cancel and an entropy remains:

Predict before you look

Use the entropy form: about how many comparisons per element does random-pivot quickselect expect for the key of rank n/4n/4 (the lower quartile) of a large array?

Show the answer

3.12

h(14)=14ln⁡4+34ln⁡43≈0.347+0.216=0.562h(\tfrac14) = \tfrac14 \ln 4 + \tfrac34 \ln \tfrac43 \approx 0.347 + 0.216 = 0.562, so the cost is about 2(1+0.562)≈3.122(1 + 0.562) \approx 3.12 comparisons per element: between the minimum's 22 and the median's 3.393.39.

No concentration. Quicksort's cost clusters tightly around its mean, but quickselect's does not: an early bad pivot wastes a constant fraction of nn comparisons, and nothing later averages it out. In 20,000 simulated searches for the median with n=105n = 10^5, the cost averaged 3.38n3.38n with a standard deviation of about 0.97n0.97n. The normalized cost C/nC/n converges to a random limit, not to a constant: in the same simulation, about one run in sixteen cost more than 5n5n.

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 3.39n3.39n to about 2.75n2.75n (Kirschenhofer, Prodinger & Martínez, 1997); our simulation agrees, with the spread shrinking too, from about 0.97n0.97n to 0.61n0.61n. 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 O(n)O(n) 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 u<vu < v 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 uu, between uu and vv, and above vv, 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.

text
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 one

A simplified Python version of this scheme, tested against sorting, used about 1.85n1.85n comparisons for the median of 10610^6 keys and about 2.24n2.24n for 10510^5: the first-order term is 1.5n1.5n, but the o(n)o(n) terms fade slowly. Careful implementations recurse to choose uu and vv and tune ss and gg.

DerivationWhy n + min(k, n − k)
  1. (n−k)⋅1+k⋅2  =  n+k  =  n+min⁡(k,n−k)(n - k) \cdot 1 + k \cdot 2 \;=\; n + k \;=\; n + \min(k, n - k)

    Take k<n/2k < n/2. Every key is compared first with vv. About n−kn - k keys exceed vv and are settled by that single comparison; only the roughly kk keys below vv need a second comparison, with uu:

  2. E[C]  =  n+min⁡(k,n−k)+o(n)\E[C] \;=\; n + \min(k, n - k) + o(n)

    Everything else is lower order. Sorting the sample costs O(slog⁡s)=O(n2/3log⁡n)O(s \log s) = O(n^{2/3} \log n). The middle part holds about 2g⋅n/s=O(n2/3log⁡n)2g \cdot n/s = O(n^{2/3} \sqrt{\log n}) keys. And the margin gg, 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 o(n)o(n):

  3. E[Cmedian]  =  1.5 n+o(n)\E[C_{\text{median}}] \;=\; 1.5\,n + o(n)

    For the median that is 1.5n+o(n)1.5n + o(n): less than half of quickselect's 3.39n3.39n, and less than the (2+ε)n(2 + \varepsilon)n that any deterministic algorithm needs in the worst case.

Check your understanding

Floyd–Rivest compares each key first with the bracket key on the side where most keys lie. For k=n/10k = n/10, about how many comparisons does the main pass make?

  1. About 1.1n1.1n
  2. About 1.9n1.9n
  3. About 2n2n
  4. About 1.5n1.5n
Show the answer

A. About 1.1n1.1n

With k=n/10k = n/10 the larger side is above vv, so every key is compared with vv first, and about 0.9n0.9n keys are settled at once; only the 0.1n0.1n keys below vv need the second comparison: 0.9n+2⋅0.1n=1.1n=n+min⁡(k,n−k)0.9n + 2 \cdot 0.1n = 1.1n = n + \min(k, n - k).

The whole picture

MethodComparisons for the medianWorst case
Quickselect, random pivot≈3.39 n\approx 3.39\,n expectedΘ(n2)\Theta(n^2), with tiny probability
Quickselect, median of 3 random keys≈2.75 n\approx 2.75\,n expectedΘ(n2)\Theta(n^2), with tiny probability
Floyd–Rivest sampling1.5 n+o(n)1.5\,n + o(n) expected, optimalnot linear unless guarded
Introselectas quickselect on typical inputsO(n)O(n)
Median of mediansdeterministic: at most ≈5.43 n\approx 5.43\,n (PICK)O(n)O(n)
Best deterministic algorithmat most 2.95 n2.95\,nO(n)O(n); at least (2+ε)n(2 + \varepsilon)n is necessary
Expected counts are over the algorithm's random choices on any input. Randomness buys a real gap here: 1.5n1.5n on average against more than 2n2n for every deterministic algorithm in the worst case.

Key takeaways

  • Random-pivot quickselect expects 2[(n+1)Hn−(n+3−k)Hn+1−k−(k+2)Hk+n+3]2[(n+1)H_n - (n+3-k)H_{n+1-k} - (k+2)H_k + n + 3] comparisons, about 2n(1+h(k/n))2n(1 + h(k/n)): 2n2n for the minimum, 3.39n3.39n for the median.
  • Its cost does not concentrate: the standard deviation is a constant fraction of nn (about 0.97n0.97n for the median), because early bad pivots are never averaged out.
  • Better pivots help (median of 3: about 2.75n2.75n), 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: n+min⁡(k,n−k)+o(n)n + \min(k, n - k) + o(n) expected comparisons, optimal by Cunto and Munro, and 1.5n1.5n for the median.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

About how many comparisons does random-pivot quickselect expect to make when k=1k = 1, finding the minimum of nn distinct keys?

  1. About nn
  2. About 2n2n
  3. About 3.39n3.39n
  4. About nlog⁡2nn \log_2 n
Show the answer

B. About 2n2n

The exact value is 2(n−Hn)2(n - H_n). Each round partitions the whole remaining range and keeps on average about half of it, so the ranges sum to about n+n/2+n/4+⋯=2nn + n/2 + n/4 + \cdots = 2n. A plain scan needs only n−1n - 1, so for extreme ranks quickselect wastes about half of its work.

Question 2

In the indicator-variable proof, when are the keys of ranks i<ji < j compared, if the target has rank kk?

  1. Exactly when one of them is the first pivot chosen among the ranks from ii to jj
  2. Always: every key is compared with every pivot
  3. Exactly when one of them is the first pivot chosen among the ranks from min⁡(i,k)\min(i, k) to max⁡(j,k)\max(j, k)
  4. Exactly when both lie on the same side of kk
Show the answer

C. Exactly when one of them is the first pivot chosen among the ranks from min⁡(i,k)\min(i, k) to max⁡(j,k)\max(j, k)

Until a pivot lands in the range spanned by ii, jj and kk, all three keys stay together. The first pivot in that range compares itself with the other two if it is ziz_i or zjz_j, and otherwise separates them or ends the search. So the probability is 2/(max⁡(j,k)−min⁡(i,k)+1)2/(\max(j, k) - \min(i, k) + 1).

Question 3

Which statement about the spread of random-pivot quickselect's cost is true?

  1. Like quicksort's, it concentrates: for large nn almost every run costs close to the mean
  2. Its standard deviation grows in proportion to nn, so C/nC/n stays random even for huge nn
  3. It is deterministic once the input is fixed
  4. Its variance is zero for the median, by symmetry
Show the answer

B. Its standard deviation grows in proportion to nn, so C/nC/n stays random even for huge nn

A bad first pivot alone can waste a constant fraction of nn comparisons, and later rounds work on ever smaller ranges that cannot compensate. Simulations for the median show a standard deviation near 0.97n0.97n, and C/nC/n converges to a random limit rather than to 3.393.39.

Question 4

For the median of nn distinct keys, what is the least expected number of comparisons a randomized algorithm can achieve on its worst input, up to lower-order terms?

  1. 2n2n
  2. 2.75n2.75n
  3. 3.39n3.39n
  4. 1.5n1.5n
Show the answer

D. 1.5n1.5n

Floyd–Rivest achieves n+min⁡(k,n−k)+o(n)=1.5n+o(n)n + \min(k, n - k) + o(n) = 1.5n + o(n) 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.