What a bound is

What derandomising costs

Randomised selection finds the median of twenty thousand elements in 3.21 comparisons per element and median-of-medians takes 8.15 — two and a half times as many for the same answer, both linear. The number that decides between them is not either of those. It is that the first varies by 28% from seed to seed and the second by 1.6%.

Selection — finding the kk-th smallest element without sorting — has a randomised algorithm everybody uses and a deterministic one everybody teaches. Both are Θ(n)\Theta(n). The deterministic one is famous for being the answer to “but what if the coin flips go badly”, and it is famous for not being used.

The usual explanation is that its constant is bad. That is true and it is not the interesting part, because the constant is only 2.54 and a factor of 2.54 is not why an algorithm goes unused. The interesting part is what the 2.54 buys, which is not the worst-case guarantee people describe it as buying.

Comparisons per element to find the median, n = 4,001, 30 seedsFor each pivot rule: the range of comparisons per element over 30 independent runs (the bar), with the mean marked. randomised pivot averages 2.96 and ranges from 1.56 to 4.12 — a factor of 2.6 on identical data, decided entirely by the coins. median of medians averages 7.94, spends no randomness, and varies by 1.7%. What derandomisation buys is not a lower cost; it is a cost that does not move.randomised pivot164 random bits2.96 ±23%median of mediansno random bits7.94 ±2%0.04.38.6comparisons per element — bar is the range over seeds, tick is the mean30 seeds, n = 4,001, median2.68× the mean, 14× the spread
Fig. 1 Comparisons per element to find the median of 4,001 elements, over thirty independent seeds. The bar is the range and the tick is the mean. Randomised selection averages 2.96 and ranges from 1.56 to 4.12 — a factor of 2.6 on identical data, decided entirely by the coins. Median-of-medians averages 7.94 and ranges from 7.69 to 8.21. One of these is an algorithm whose cost is predictable.

The two algorithms

Randomised quickselect. Pick a pivot uniformly at random from the current range, partition, and recurse into whichever side contains the target. The expected number of comparisons is 2n(1+ln2)3.39n2n(1 + \ln 2) \approx 3.39n for the median, and the derivation is a short recurrence. On any input.

Median of medians, from Blum, Floyd, Pratt, Rivest and Tarjan. Split the range into groups of five, sort each group, take the median of each group, and recursively select the median of those medians; use that as the pivot. The pivot is then guaranteed to be between the 30th and 70th percentiles, so the recursion shrinks by at least 30% every time and the total is Θ(n)\Theta(n) in the worst case — deterministically, with no coins anywhere.

Both are linear. The difference in the class is what the linearity is a statement about: for the first it is an expectation over the coins, and for the second it is a bound over every input.

What forty seeds say

The measurement is thirty to forty independent runs at each size, because one run of a randomised algorithm is an anecdote and this is the algorithm where that bites hardest.

nn rule mean per element min max spread random bits
4,001 random pivot 2.96 1.56 4.12 23.2% 164
4,001 median of medians 7.94 7.69 8.21 1.7% 0
20,001 random pivot 3.27 1.77 5.21 24.6% 246
20,001 median of medians 8.11 7.29 8.33 3.0% 0

Three results, and the third is the one this essay is about.

The constants are 3.21 and 8.15, averaged over forty seeds at n=20,001n = 20{,}001. The randomised measurement lands close to the theoretical 3.39n3.39n; the deterministic one is 2.54 times it. Both are honestly linear over the range measured.

The deterministic rule spends zero random bits, which is a measurement here rather than a remark about the source code, because the site counts them. The randomised rule spends 246 per run at n=20,001n = 20{,}001 — a small number, and not zero.

And the spreads are 27.7% and 1.6%. That is the finding. The randomised algorithm’s cost on identical data varies by a factor of three depending on nothing but the seed; the deterministic algorithm’s barely varies at all, and what variation it has comes from the data rather than from anything internal.

Where the 8.15 comes from

A constant of 2.54× is worth accounting for, because the components are visible in the algorithm and the total is a check on whether it is implemented as described.

Per level of the outer recursion on a range of size ss, median-of-medians does three things:

Sorts s/5s/5 groups of five. Insertion sort on five elements averages about 7.7 comparisons, so this is 7.7×s/51.54s7.7 \times s/5 \approx 1.54s. This is the largest single component and it is the reason groups of five rather than three: groups of three make the guaranteed split too weak for the recursion to be linear at all, and groups of seven cost more per group than the tighter split saves.

Selects the median of the s/5s/5 medians, recursively. By the same accounting that is about 2.5×s/5=0.5s2.5 \times s/5 = 0.5s once the recursion is unrolled.

Partitions the range. ss comparisons.

That is roughly 3s3s per level. The guaranteed split is at worst 70/30 and is typically much better than the guarantee — the median of medians of a random array is usually close to the true median — so in practice the range roughly halves each level and the total is about 3s×2=6s3s \times 2 = 6s, plus the recursive median subproblems. The measured 8.15 is in that neighbourhood, and the gap between 8.15 and the 24 or so the worst-case analysis gives is the difference between the guaranteed split and the typical one.

So median-of-medians is, in practice, running at about a third of its own worst-case constant — which is itself a mildly interesting fact, because the whole point of the algorithm is that the worst case is bounded, and the bound it is famous for is three times what it usually costs.

Which is why the folklore is the wrong way round

The standard framing is that median-of-medians is the safe choice and randomised quickselect is the fast one, with the safety being about the worst case — the vanishingly improbable run where every pivot is terrible.

That framing gets the risk in the wrong place. The worst case of randomised quickselect is Θ(n2)\Theta(n^2) and its probability is somewhere around 2n2^{-n}; nobody has ever seen one and nobody ever will. What people actually experience is the measured distribution above: a run that costs 1.6 times the mean, which happens routinely, and which at 24.6% relative spread happens often enough to appear in any sample of a few dozen runs.

So the honest statement of the trade is:

  • Not “randomised is fast and might be catastrophic”.
  • But “randomised is 2.5 times cheaper on average and 60% more expensive than its own average on a bad day; deterministic is 2.5 times more expensive always, and always means always”.

Which of those two is preferable depends entirely on whether the thing being budgeted is throughput or latency. For throughput — total work over many operations — the randomised version wins outright, because the average is what accumulates and the average is 2.5 times better. For a tail latency target — a 99th percentile that must be met — the comparison is between the randomised algorithm’s 99th percentile and the deterministic algorithm’s flat cost, and at n=20,001n = 20{,}001 those are 5.21 and 8.33 comparisons per element. The randomised one still wins, and by less.

Why the spread is so different

The reason the two distributions are shaped so differently is worth a paragraph, because it generalises past selection.

Randomised quickselect’s cost is dominated by its first few pivots. The first partition costs nn comparisons whatever happens, and then the size of the remaining problem is decided by one draw. A first pivot at the 5th percentile leaves 95% of the array; one at the 50th leaves 50%. The whole rest of the run is scaled by that single decision, so the total is essentially a product of a handful of random factors and it has the variance of a product.

Median-of-medians has no such decision. Every pivot is guaranteed to be between the 30th and 70th percentiles, so the shrinkage per level is bounded on both sides and the total is a sum of tightly constrained terms. Its 1.6% residual variation is the data, not the algorithm.

The general rule this suggests, and which the skip list essay arrives at from the other direction: a randomised algorithm concentrates when its cost is a sum of many independent contributions, and does not when its cost turns on a few. A skip list search is a sum over logn\log n levels and concentrates to 6%; a randomised selection is a product over a handful of pivots and spreads to 25%. Both have clean expected bounds. Only the first one’s bound is a prediction.

Comparisons per element to find the median, n = 4,001, 20 seedsFor each pivot rule: the range of comparisons per element over 20 independent runs (the bar), with the mean marked. randomised pivot averages 3.06 and ranges from 1.56 to 4.12 — a factor of 2.6 on identical data, decided entirely by the coins. median of medians averages 7.92, spends no randomness, and varies by 1.6%. What derandomisation buys is not a lower cost; it is a cost that does not move.randomised pivot167 random bits3.06 ±22%first-element pivotno random bits3.37 ±36%median of mediansno random bits7.92 ±2%0.04.38.6comparisons per element — bar is the range over seeds, tick is the mean20 seeds, n = 4,001, median2.59× the mean, 14× the spread
Fig. 2 The third rule, included for what it is not. A first-element pivot on random input is perfectly respectable — it is a random pivot, since the data is random — and it sits alongside the randomised rule. Its bad case is not visible here because its bad case is sorted input, where it costs 3,000 comparisons per element against the randomised rule’s 4.86. A benchmark on random data reports the deterministic rule and the randomised one as equivalent, which is the entire argument of expected is not average in one figure.

The measurement that nearly went wrong

The assertion behind these numbers originally compared one randomised run against one deterministic run at n=20,001n = 20{,}001, and demanded a factor of at least two.

It failed, at 1.40×. The randomised run had drawn a bad seed — 5.7 comparisons per element against its own mean of 3.2 — and the assertion concluded there was no price to derandomisation.

That is the same error the algorithm’s users make, made by a test: a single run of a randomised algorithm cannot support a statement about its cost, and an assertion that takes one is measuring the seed. Over forty seeds the two numbers separate cleanly at 2.54 and the assertion has never wobbled since. The rewritten version also checks the spreads, requiring the randomised rule’s relative standard deviation to be at least five times the deterministic one’s — which is the actual finding, and which the original assertion did not look at.

Worth noting what the failure did not look like. Nothing crashed, no figure drew wrongly, and the number 1.40 is perfectly plausible. Had the tolerance been set at 1.2 rather than 2, the assertion would have passed, the essay would have reported a 40% cost for derandomisation, and it would have been wrong by a factor of nearly two with no indication anywhere.

The other deterministic rule, and why it is not the answer

There is a much cheaper deterministic pivot rule than median-of-medians, and it is the one real libraries actually reach for first: take the first element, or the middle one, or the median of three of them. Those cost essentially nothing and they are deterministic.

They are also not a derandomisation of anything. A first-element pivot on random input is indistinguishable from a random pivot — the figure above shows it sitting alongside the randomised rule, because when the data is random, taking a fixed position is taking a random element. What it lacks is the guarantee, and the lack shows up on exactly one input. At n=8,001n = 8{,}001 on sorted data:

rule comparisons per element
random pivot 38,856 4.86
median of medians 46,223 5.78
first element 24,006,000 3,000.37

Three thousand comparisons per element, which is n/2n/2 per element, which is the quadratic behaviour written out. The cheap deterministic rule is not a middle option between the other two; it is a fourth thing entirely, with the randomised rule’s constant on ordinary data and no bound at all on the input it cannot handle.

That is worth stating because “deterministic” covers both of the deterministic rules here and they have nothing in common. One has a proved worst-case linear bound and costs 2.5×; the other has no bound and costs nothing. Choosing “the deterministic one” is not a choice until which one is named.

What the deterministic algorithm is actually for

Having spent the essay arguing that the folklore reason is wrong, here is the case for it that survives.

When the input is adversarial and the seed is not secret. The whole of the preceding essay is about how completely a randomised guarantee evaporates when the coins are known. A deterministic algorithm with a worst-case bound does not have that failure mode, because it has no coins to learn. In an environment where secret randomness is genuinely unavailable — some embedded systems, some formally verified contexts — median-of-medians is the answer and its 2.54 is the price.

When the bound has to be provable rather than measured. A real-time system certified against a worst-case execution time cannot use a bound that holds with probability 12n1 - 2^{-n}, because the certification does not have a place to put the probability. This is a legitimate and narrow requirement and it is the one median-of-medians actually meets.

As the fallback half of a hybrid. Introselect — run randomised quickselect, and if the recursion depth exceeds a threshold, switch to median-of-medians — gets the randomised constant almost always and the deterministic bound always. That is what real libraries do, and it is the same shape as introsort’s depth limit: use the fast algorithm and keep the slow one as insurance that is almost never claimed on.

Three structures on the input chosen against them, n = 2,048Each pair is one problem, solved deterministically and randomly, measured on the input that is worst for the deterministic version. The bars are logarithmic because the pairs are: 83×, 79×, 205×. The deterministic guarantees are all average-case ones — true of most inputs, and about the data. The randomised guarantees are expected-case, true of every input, and about the algorithm's own coins. Only the second kind survives somebody choosing the input.quicksort on sorted input — comparisonsfirst-element pivot2,096,128random pivot25,318a search tree built from sorted keys — heightbinary search tree2,047treap26a hash table on keys chosen to collide — worst bucketthe low bits of the key2,048multiply–shift, a at random10n = 2,048, bars on a logarithmic scaledeterministic above, randomised below
Fig. 3 And the case derandomisation is not needed for. Three deterministic structures against their randomised counterparts, on the input chosen against the deterministic one — 83×, 79× and 205×. Randomising fixes all three at negligible cost. Median-of-medians is the opposite kind of answer to the same kind of problem: it removes the coins instead of adding them, and it is the one that costs 2.5× rather than nothing.

Why five, and the sweep that is not run here

The group size is a parameter, it is always five, and the reason is arithmetic that the accounting above has most of the pieces for. It is worth assembling, because it explains why the constant is as large as it is and why it cannot be tuned down.

The recursion has two calls: one on the n/gn/g medians, and one on whatever survives the partition. Linearity requires those two fractions to sum to less than one — if they reach one, the recursion does the same amount of work at every level and the total is Θ(nlogn)\Theta(n\log n) rather than Θ(n)\Theta(n).

With groups of gg, the pivot is guaranteed to beat about half the group medians, each of which beats about half its own group, so roughly a quarter of the elements are eliminated and about three quarters survive. The median subproblem is 1/g1/g. So the condition is approximately

1g+34<1\frac{1}{g} + \frac{3}{4} < 1

which fails at g=3g = 3 — a third plus three quarters is over one — and holds from g=5g = 5 upward. That is the whole reason groups of three do not work, and it is a statement about a sum of two fractions rather than anything subtle about medians.

So why not seven, or nine? Because the term that grows is the group sort. Sorting a group of gg by insertion costs about g2/4g^2/4 comparisons, and there are n/gn/g groups, so the group-sorting work is about ng/4ng/4linear in the group size. Going from five to seven raises that term by 40% and improves the eliminated fraction only slightly, since the guarantee approaches a quarter and stops. Five is the smallest size that works, and because the dominant cost grows with gg, the smallest size that works is also the cheapest.

That accounts for the largest component of the 8.15: the group sort alone is about 1.54n1.54n per level of a recursion several levels deep, and it is there because the algorithm needs a guaranteed median of each group rather than a sample of one.

None of the above is measured on this page. It is a derivation from the recurrence, offered because it says what the constant is made of and where it would move; a sweep over group sizes would be a genuine measurement and it is not run here, so the numbers for seven and nine are absent rather than estimated. What can be said from the measurements is that the total at g=5g = 5 is 8.15 comparisons per element, and that the group sort is the largest single term inside it.

The constants at three sizes

The two rules differ by a constant, and a constant is a claim about a sweep rather than about a size.

Comparisons per element to find the median, n = 1,001, 30 seedsFor each pivot rule: the range of comparisons per element over 30 independent runs (the bar), with the mean marked. randomised pivot averages 3.47 and ranges from 1.95 to 6.55 — a factor of 3.4 on identical data, decided entirely by the coins. median of medians averages 7.49, spends no randomness, and varies by 3.1%. What derandomisation buys is not a lower cost; it is a cost that does not move.randomised pivot123 random bits3.47 ±29%median of mediansno random bits7.49 ±3%0.04.18.3comparisons per element — bar is the range over seeds, tick is the mean30 seeds, n = 1,001, median2.16× the mean, 9× the spread
Fig. 4 A quarter of the array. Comparisons per element to find the median, thirty seeds, the two rules side by side.
Comparisons per element to find the median, n = 16,001, 20 seedsFor each pivot rule: the range of comparisons per element over 20 independent runs (the bar), with the mean marked. randomised pivot averages 3.29 and ranges from 2.12 to 5.98 — a factor of 2.8 on identical data, decided entirely by the coins. median of medians averages 8.09, spends no randomness, and varies by 1.9%. What derandomisation buys is not a lower cost; it is a cost that does not move.randomised pivot230 random bits3.29 ±29%median of mediansno random bits8.09 ±2%0.04.48.8comparisons per element — bar is the range over seeds, tick is the mean20 seeds, n = 16,001, median2.46× the mean, 15× the spread
Fig. 5 And four times it. The per-element counts barely move, which is what “linear” means when it is measured rather than asserted, and the gap between the two rules does not move either.

The third variation holds the size fixed and changes how many draws went into the picture, which is the parameter that decides how much of the randomised rule’s distribution is visible at all.

Comparisons per element to find the median, n = 4,001, 100 seedsFor each pivot rule: the range of comparisons per element over 100 independent runs (the bar), with the mean marked. randomised pivot averages 3.30 and ranges from 1.64 to 6.32 — a factor of 3.9 on identical data, decided entirely by the coins. median of medians averages 7.86, spends no randomness, and varies by 5.7%. What derandomisation buys is not a lower cost; it is a cost that does not move.randomised pivot165 random bits3.30 ±28%median of mediansno random bits7.86 ±6%0.04.38.6comparisons per element — bar is the range over seeds, tick is the mean100 seeds, n = 4,001, median2.38× the mean, 5× the spread
Fig. 6 The original size over a hundred seeds rather than thirty, starting from a different one. More seeds fill the randomised rule’s spread out and leave the deterministic rule’s single point where it was — which is the difference the whole page is about.

The honest limits

Two, both about what the range of the measurement supports.

Linearity is fitted, not established. Both algorithms’ comparison counts are measured at 4,001 and 20,001 and fitted linear over that range. That is the site’s standing limit: a finite sample cannot establish an asymptotic claim, and what is being reported is that the counts are linear over the sizes measured, with the constants stated. The worst-case linearity of median-of-medians is a theorem and does not depend on the measurement; the expected linearity of randomised quickselect is also a theorem; what the measurement adds is both constants, which no theorem gives.

Forty seeds see nothing rarer than one in forty. The 27.7% spread and the maximum of 5.84 comparisons per element are properties of a forty-run sample. Whether randomised quickselect can produce a run costing ten times its mean is not a question forty runs answer, and the theory says the probability decays exponentially. So “the worst observed” is what the figures report, and the worst possible is not measured and is not claimed.

Where insertion sort actually wins — and it is not in the comparisonsMean over 60 random inputs at each size, both counts on one pair of axes. Insertion sort performs more comparisons than Merge sort at every size measured, including n = 4: the dashed pair never cross. The solid pair — total reads and writes — do cross, between n = 12 and n = 16. The familiar advice to fall back to insertion sort on small subarrays is right, and the reason is memory traffic rather than comparisons, which is a distinction the usual telling of it loses.481632641281010010³10⁴noperations (mean of 60 runs)Insertion trafficMerge trafficInsertion cmpMerge cmptraffic crossessolid: reads + writes · dashed: comparisonstraffic crosses between n = 12 and 16; comparisons never do
Fig. 7 A third kind of answer to the same question, for scale. Insertion sort makes more comparisons than merge sort at every size measured, including n = 4, and the total reads and writes cross between n = 12 and n = 16 — so the standard advice to fall back to insertion sort on small subarrays is right for a reason the comparison count cannot see. Choosing between algorithms is decided by which quantity is being counted, whether that quantity is memory traffic or variance.

The shape of the result

Set the phase’s two directions side by side, because this essay is the second one and the first is everywhere else in it.

Adding randomness to quicksort’s pivot, to a search tree’s balance, to a hash table’s bucket choice: costs almost nothing measurable — two bits per key, thirty-two bits per key, one multiply — and removes a catastrophic input each time.

Removing randomness from selection: costs 2.54 times the comparisons and removes a variance of 28%.

Both are worth doing in the right circumstances and neither is free, and the reason to have both numbers is that the circumstances are decided by which resource is scarce. What the measurement adds to the textbook account is that the second trade is not the one it is usually described as. Derandomisation is not sold as variance reduction and that is exactly what it is: the deterministic algorithm is slower on every input including the good ones, and what it buys is that the cost stops depending on anything outside the program’s control.

Named alongside this one

Essays reaching for the same objects. Nobody chose these; they are what the concept index makes visible.

What links here

Every essay whose body links to this one.

The objects this essay names

Each one links to every other essay that touches it.

DerandomisationDistributionGuaranteeMedian of mediansPartitionPivotQuickselectRandomised algorithmSkip listVarianceWorst case