Counting

The spread a merge sort does not have

On 65,536 random keys quicksort's comparison count has a standard deviation of 42,470 and merge sort's has one of 141.9 — three hundred times smaller, on means only a quarter apart. Merge sort's count is a fixed bill minus 65,535 independent leftovers, one per merge, each worth about a coin toss, so its spread grows as the square root of n where quicksort's grows as n. From 256 keys up a single run of merge sort pins its mean to one per cent, and a third of quicksort's whole spread is decided by its first pivot.

A distribution computed rather than sampled took quicksort’s comparison count apart pivot by pivot and weighed every outcome, and found on sixty-four keys a mean of 360.706 and a standard deviation of 36.741. It then used those two numbers to answer a practical question — how many runs a sampled mean needs before it can be trusted — and the answer was hundreds at small sizes, falling only slowly as the input grew.

That page was about quicksort because quicksort is the famous randomised sort, and its randomness is the algorithm’s own: the pivot is a coin it tosses. Merge sort tosses no coins. Given an input, it makes exactly one number of comparisons, and a count over every input listed that number for all 40,320 orders of eight keys. Hand it a random input, though, and its count becomes a random variable too, drawn from a distribution over inputs rather than over pivots — and that distribution is the one every benchmark on random data is actually sampling.

This page computes it, exactly, and sets it beside quicksort’s. The two means are a quarter apart. The two spreads differ by a factor that grows without limit, and the reason is visible in the structure of the two recursions before any number is computed.

What one merge leaves over

Merge sort’s merge takes two sorted runs of aa and bb keys and compares their front keys until one run is empty. After that the other run’s remainder is copied across with no comparisons at all. So a merge makes a+bTa + b - T comparisons, where TT is the number of keys still waiting on the other side when the first side runs out. TT is at least one: the last key of the merged output is never compared against anything after it.

On a random input, every way of interleaving the two runs is equally likely — there are (a+ba)\binom{a+b}{a} of them — and TT is the length of the final stretch of the interleaving that comes from one side. The probability that the last tt keys all came from the left run is (a+btb)/(a+ba)\binom{a+b-t}{b} / \binom{a+b}{a}, and the mirror expression gives the right run. Both can be computed as running products without ever forming a binomial.

One merge of 512 keys against 512 leaves 1.996 keys over on average, and a merge of 4 against 4 leaves 1.600The number of keys still waiting on the other side when a merge's first side runs out, which is how many comparisons the merge saves against its full a + b − 1. On a random input every interleaving of the two runs is equally likely. Merging 4 against 4: one left over with probability 0.571, two with 0.286, three with 0.114; mean 1.600, variance 0.640. Merging 512 against 512: one left over with probability 0.500, two with 0.250, three with 0.125; mean 1.996, variance 1.981. The smaller merge is checked against all 70 of its interleavings. The larger is very nearly a coin tossed until it comes up differently: a half, a quarter, an eighth, with mean and variance both two.0.00.10.20.30.40.50.6123456789keys left over when one side runs outprobability4 against 4512 against 512mean 1.600mean 1.996the smaller checked against all 70 interleavingsa merge saves T − 1 comparisons
Fig. 1 How many keys are left over when one side of a merge runs out, for a merge of 4 against 4 and of 512 against 512. The small merge is checked against all 70 of its interleavings: one key left over with probability 0.571, two with 0.286, three with 0.114. The large merge is almost exactly a coin tossed until it comes up differently — a half, a quarter, an eighth — with mean 1.996 and variance 1.981.

For a large balanced merge, the leftover is very nearly geometric. The last key came from one side; the key before it came from the same side with probability about a half; the one before that, a half again. Mean two, variance two, and almost no chance of more than a dozen. That is the entire random content of a merge: a quantity of order one, with a spread of order one, regardless of how many keys the merge handles.

For small merges it is smaller still. A merge of one key against one always leaves exactly one over, so it contributes no randomness at all. A merge of two against two leaves one over with probability two thirds and two with probability one third: variance 0.222. Four against four, 0.640. Eight against eight, 1.106. The variance climbs towards two as the runs lengthen and never passes it.

The step that makes merge sort’s count tractable is that these leftovers are independent. On a random permutation, the order of keys inside the left half, the order inside the right half and the way the two halves interleave are three independent facts. Recursively, every merge in the sort sees an interleaving that is uniform and independent of every other merge’s. So merge sort’s comparison count is a fixed bill — the sum of a+ba + b over every merge — minus a sum of 65,535 independent leftovers at 65,536 keys, and its whole distribution is a convolution of 65,535 small distributions, of which — at a power of two — only sixteen are different.

The distribution, and real runs laid over it

Convolving is cheap because the top-down split produces at most two distinct run sizes at each level. The count on nn keys is the count on n/2\lfloor n/2 \rfloor keys plus the count on n/2\lceil n/2 \rceil keys plus one merge, all three independent, so each distinct size costs two convolutions. At 65,536 keys the array is 2,582 entries long, and the calculation takes milliseconds.

Merge sort on 1,024 random keys: mean 8947.15 comparisons, standard deviation 17.68The exact probability of each comparison count for top-down merge sort on 1,024 distinct keys in random order, computed by convolving the leftover of every one of its 1,023 merges rather than by running anything. Mean 8947.151, standard deviation 17.683 — 0.20% of the mean. The bars are 400 real runs of the implementation on seeded random permutations, binned 3 comparisons wide: their mean is 8946.16, and 379 of the 400 land within two standard deviations of the exact mean. The whole distribution sits between 8,878 and 9,010 for all but two parts in ten thousand.00.0100.0200.030comparisonsprobability of exactly that many8,9008,9509,000mean 8947.15exact400 runsn = 1,024, distinct keys, random ordersampled mean 8946.16
Fig. 2 Merge sort on 1,024 random distinct keys. The curve is the exact probability of each comparison count, convolved merge by merge: mean 8,947.151, standard deviation 17.683. The bars are 400 real runs of the implementation on seeded random permutations. Their mean is 8,946.16, about one standard error from the exact value, and all but two in ten thousand outcomes lie between 8,878 and 9,010.

Three routes lead to the same distribution, and all three agree. The convolution gives a probability for every count. The cumulants — mean, variance and third central moment — can instead be summed merge by merge, because cumulants of independent pieces add, and they match the convolution’s to within one part in ten million at every size tried. At eight keys the distribution multiplied by 8!8! must reproduce, integer for integer, the histogram a count over every input obtained by running merge sort on all 40,320 orders. It does. And real runs land where the curve says: 400 of them on 1,024 keys average 8,946.16 against an exact 8,947.15.

The standard deviation at 1,024 keys is 17.683 comparisons, which is 0.20% of the mean. On the same keys quicksort’s is 655, or 5.8% of its mean. The next plate puts both on one axis, at a size where both distributions can be computed exactly.

Two distributions on the same keys

On 64 random keys quicksort's comparison count spreads 8.7 times as wide as merge sort'sThe exact distribution of the comparison count of top-down merge sort and of quicksort with a uniformly random pivot, on the same 64 distinct keys in random order, both computed rather than sampled. Merge sort: mean 305.05, standard deviation 4.22, every outcome between its best case of 192 and its worst of 321. Quicksort: mean 360.71, standard deviation 36.74, with a long right tail — its 99.99th percentile is 575. The narrow peak is merge sort; its tallest bar reaches 0.095 and quicksort's 0.012.00.0250.0500.0750.100200300400500comparisonsprobability of exactly that manymerge sort's worst case, 321merge sort, sd 4.22quicksort, sd 36.74n = 64, both exactratio of spreads 8.7
Fig. 3 The exact distributions of merge sort’s and quicksort’s comparison counts on the same 64 random distinct keys, both computed rather than sampled. Merge sort: mean 305.05, standard deviation 4.22, every outcome between its best case of 192 and its worst of 321. Quicksort: mean 360.71, standard deviation 36.74, and a long right tail reaching 575 at the 99.99th percentile. The spreads differ by a factor of 8.7.

At sixty-four keys the shapes already say most of it. Merge sort’s count is a tall narrow spike a little to the left of its own worst case. Quicksort’s is a low wide hump whose right tail runs past the whole of merge sort’s range, and past its worst case too: 88% of quicksort’s runs on these sixty-four keys make more comparisons than merge sort can make on any input at all.

The factor of 8.7 between the spreads is not a constant of the two algorithms. It is 8.7 at 64 keys, 37 at 1,024 and 299 at 65,536, and it keeps growing, because the two spreads obey different laws.

One spread grows as n and the other as its square root

At 65,536 keys quicksort's standard deviation is 42,470 comparisons and merge sort's is 141.9The standard deviation of each sort's comparison count on random input, computed exactly, against the number of keys on logarithmic axes. Merge sort: 1.8, 4.2, 8.8, 17.7, 35.5, 70.9, 141.9 at 16, 64, 256, 1,024, 4,096, 16,384, 65,536 keys — doubling for every fourfold increase, which is growth as the square root of n. Quicksort: 7, 37, 159, 655, 2,645, 10,608, 42,470 — quadrupling, which is growth in proportion to n. At 65,536 keys the two means are 965,708 and 1,267,172, a quarter apart, and the two spreads are 299 times apart.16642561,0244,09616,38465,5361010010³10⁴keys sortedstandard deviation of the comparison countquicksort: grows as nmerge sort: grows as √nexact moments, distinct keys in random orderratio 299 at 65,536
Fig. 4 The standard deviation of each sort’s comparison count on random input, computed exactly, on logarithmic axes. Merge sort: 1.8, 4.2, 8.8, 17.7, 35.5, 70.9 and 141.9 at 16, 64, 256, 1,024, 4,096, 16,384 and 65,536 keys — doubling with every fourfold increase. Quicksort: 7, 37, 159, 655, 2,645, 10,608 and 42,470 — quadrupling. At 65,536 keys the means are 965,708 and 1,267,172 and the spreads are 299 times apart.

The slopes on the logarithmic plot are one half and one. Merge sort’s spread doubles every time the input quadruples, which is growth as n\sqrt{n}. Quicksort’s quadruples, which is growth in proportion to nn. Its variance has a closed form, 7n24(n+1)2Hn(2)2(n+1)Hn+13n7n^2 - 4(n+1)^2 H_n^{(2)} - 2(n+1)H_n + 13n, which Knuth gives and which agrees here with the recurrence at every size up to 2,048. Its leading term is (72π2/3)n20.420n2(7 - 2\pi^2/3)\,n^2 \approx 0.420\,n^2.

Merge sort’s follows from the leftovers without any further algebra. Its variance is the sum of the leftovers’ variances. There are about n/2k+1n/2^{k+1} merges of 2k2^k keys a side, and each contributes a variance that climbs from 0 for the smallest towards 2 for the largest, so the total is nn times a convergent sum — about 0.31n0.31\,n. The square root of 0.31n0.31\,n at 65,536 keys is 142, and that is the number on the plate.

The laws are different because the two sums are different kinds of sum. Merge sort’s randomness is a sum of many pieces, each of order one and each independent of the rest. Quicksort’s randomness is not like that at all. Its first pivot decides how the whole of the rest of the work divides. A first pivot landing at the quarter point instead of the middle changes the expected remaining cost by an amount proportional to nn, and nothing later averages that away, because nothing later is independent of it.

Where in the recursion the spread is made

That difference can be measured rather than argued. Variances of independent pieces add, so merge sort’s variance splits exactly into what each level of merges contributes. Quicksort’s splits by the law of total variance: the share its first pivot decides is the variance, over that pivot, of the expected count given it; the rest is the same split one level down, averaged over the first pivot.

The top three levels of quicksort's recursion decide 71% of its spread; the top three levels of merge sort's decide 1.1%The share of each sort's comparison-count variance decided at each depth of its recursion on 4,096 random keys, from the top. For quicksort a depth is a level of pivot choices, split by the law of total variance: the first pivot alone decides 33.6%, the two below it 22.4%, the four below those 14.9%, each level two thirds of the one above. For merge sort a depth is a level of merges and the shares are simply their variances added: the final merge of two halves decides 0.16%, and the largest share, 26.1%, belongs to the 512 merges of 4 keys against 4 at depth 9. Merges of two to sixteen keys a side decide 82% between them.0%10%20%30%40%01234567891011204810245122561286432168421deptha sidedepth in the recursion, from the top — and the keys a side in merge sort's merges thereshare of the variance decided therequicksort: the first pivot, 33.6%merge sort: 4 against 4, 26.1%n = 4,096, exactvariance split by depth
Fig. 5 The share of each sort’s comparison-count variance decided at each depth of its recursion on 4,096 random keys, from the top. Quicksort’s first pivot alone decides 33.6%, the two pivots below it 22.4%, the four below those 14.9% — each level two thirds of the one above. Merge sort’s final merge of two halves decides 0.16%, its top three levels 1.1%, and its 512 merges of four keys against four decide 26.1%; merges of two to sixteen keys a side decide 82% between them.

Quicksort’s spread is made at the top and merge sort’s is made at the bottom. One random choice — the first pivot — accounts for a third of quicksort’s whole variance at 4,096 keys, and 33.4% of it at 65,536. The top three levels, seven pivot choices out of about four thousand, account for 71%.

The two thirds between successive levels has a one-line explanation. A subproblem of mm keys contributes, at its own top level, a variance proportional to m2m^2, because its pivot moves its expected cost by an amount proportional to mm. One level down, its two children have sizes UU and m1Um - 1 - U with UU uniform, and the expected sum of their squares is two thirds of m2m^2. So each level holds two thirds of the variance of the level above, a geometric series that puts most of the weight within a few levels of the root.

Merge sort’s shares run the other way. The final merge of two 2,048-key halves is the largest single merge and contributes a variance of two, which is 0.16% of the total, because there is only one of it. Each level down has twice as many merges and each has a variance only slightly below two, so the shares double level by level — until the merges get small enough that their leftovers stop being random. The peak is merges of four keys against four, and below that it falls away to nothing, because a merge of one key against one is not random at all.

That is the structural reason one spread is n\sqrt{n} and the other nn. A sum dominated by a few large terms has a spread the size of its largest term. A sum of many small, independent, comparable terms has a spread the size of the square root of their number.

A bell, and a tail that does not go away

The same distinction decides the shape. A sum of many small independent pieces tends to a normal curve — symmetric, with thin tails — and the rate at which it gets there can be read off its skewness, the third central moment divided by the cube of the standard deviation. A symmetric bell has skewness zero.

Quicksort's count keeps a skewness of 0.859 at 8,192 keys; merge sort's has fallen to −0.030The skewness — third central moment over the cube of the standard deviation — of each sort's comparison count on random input, computed exactly, against the number of keys on a doubling scale. A symmetric bell has skewness zero. Quicksort: 1.077, 1.041, 0.989, 0.945, 0.913, 0.891, 0.876, 0.868, 0.862, 0.859 at 16, 32, 64, 128, 256, 512, 1,024, 2,048, 4,096, 8,192 keys, settling towards a positive constant, so its count keeps a long right tail at every size. Merge sort: −0.557, −0.432, −0.321, −0.233, −0.167, −0.119, −0.084, −0.060, −0.042, −0.030, negative and halving with every fourfold increase, which is what a sum of many small independent pieces does on its way to a normal curve.-0.50000.5001keys sortedskewness of the comparison count1632641282565121,0242,0484,0968,192Quicksort, random pivotMerge sort0: a symmetric bellexact third moments, distinct keysquicksort 0.859, merge sort −0.030
Fig. 6 The skewness of each sort’s comparison count on random input, computed exactly, on a doubling scale from 16 to 8,192 keys. Quicksort: 1.077 at 16 keys, 0.989 at 64, 0.876 at 1,024, 0.859 at 8,192 — settling towards a positive constant, so its count keeps a long right tail at every size. Merge sort: −0.557, −0.321, −0.084, −0.030 — negative, and halving with every fourfold increase.

Merge sort’s skewness is negative because each merge’s leftover has a right-hand tail — occasionally a merge leaves seven or eight keys over — and the leftover is subtracted from the bill, so the tail points left. It halves every time the input quadruples, which is the 1/n1/\sqrt{n} rate at which a sum of independent pieces loses its asymmetry. By 8,192 keys it is −0.030, and the distribution is a bell for every practical purpose. Flajolet and Golin proved in 1994 that the limit is exactly normal; the plate shows the approach rather than the limit.

Quicksort’s skewness does not go to zero. The third moments here come from the same recurrence over the pivot’s rank that gave the variance, checked against the exact distribution at 8, 32 and 64 keys, and they settle near 0.86. That the limit law is not normal at all is a theorem of Régnier and Rösler from around 1990: normalised by nn, quicksort’s comparison count converges to a fixed skewed distribution of its own. The mechanism is the one the previous plate drew. A count decided mostly by a few early choices inherits their shape, and an unlucky first pivot is a large, lopsided event that no amount of later averaging can make symmetric.

For merge sort, the practical meaning of a bell is that the standard deviation is the whole story. Four standard deviations cover all but one run in fifteen thousand. For quicksort the long right tail means a standard deviation understates how far the bad runs go, and on average is not a number made that point about quicksort by sampling it. Here it is a property of the limit, not an accident of the sample.

What a benchmark needs to run

A distribution computed rather than sampled turned quicksort’s exact moments into a count of runs: how many independent runs a sampled mean needs to land within a stated fraction of the true mean 95% of the time. The rule is (1.96σ/(pμ))2(1.96 \cdot \sigma / (p \cdot \mu))^2, and it depends only on the coefficient of variation σ/μ\sigma/\mu. That ratio is where the two laws above show up as a working difference.

From 256 keys up one run of merge sort pins its mean to ±1%; quicksort still needs 44 at 65,536How many independent runs a sampled mean needs to land within a stated fraction of the true mean 95% of the time, (1.96 · sd ÷ (precision · mean))², from the exact moments. Quicksort, random pivot to ±1%: 793, 399, 217, 130, 85, 59, 44. Merge sort to ±1%: 61, 8, 1, 1, 1, 1, 1. Quicksort, random pivot to ±0.1%: 79,265, 39,858, 21,612, 12,919, 8,416, 5,871, 4,316. Merge sort to ±0.1%: 6,028, 734, 99, 16, 3, 1, 1 — at 16, 64, 256, 1,024, 4,096, 16,384, 65,536 keys. Merge sort's line falls to one run and stays there; quicksort's falls only as slowly as the logarithm of n rises.16642561,0244,09616,38465,53611010010³10⁴keys sortedruns needed, 95% of the timequicksort, ±1%merge sort, both precisionsquicksort, ±0.1%from the exact moments, not from runsdashed: the tighter precision
Fig. 7 Runs needed for a sampled mean to land within ±1% and ±0.1% of the true mean 95% of the time, from the exact moments. Merge sort to ±1%: 61 runs at 16 keys, 8 at 64, and one from 256 keys upwards. Quicksort to ±1%: 793, 399, 217, 130, 85, 59 and 44. To ±0.1%, merge sort needs 99 runs at 256 keys and one from 16,384 up; quicksort needs 4,316 even at 65,536.

Merge sort’s coefficient of variation falls like 1/(nlogn)1/(\sqrt{n}\log n): the spread grows as n\sqrt{n} and the mean as nlognn \log n. Quicksort’s falls only like 1/logn1/\log n, since both its spread and its mean are close to proportional to nn and only the logarithm in the mean separates them. At 65,536 keys merge sort’s is 0.015% and quicksort’s is 3.4%.

Counting instead of timing made every count here reproducible to the last digit on a fixed input. On random inputs the question is how much one input can stand for all of them, and the answer differs between the two sorts. So from 256 keys up, one run of merge sort on a random input measures its mean to within one per cent, and from 16,384 keys to within a tenth of one per cent. A single run is not a sample from merge sort’s distribution in any sense that matters; it is a measurement of its mean. One run of quicksort at 65,536 keys is a draw whose standard deviation, 42,470 comparisons, is more than three times the whole of that one per cent.

That changes what a comparison between the two can say. The two means at 65,536 keys stand in the ratio 1.312: quicksort with a random pivot makes 31% more comparisons than merge sort, on average. A benchmark that ran each once and reported the ratio could get anything from 22% to 40% more at two standard deviations either side, and all of that uncertainty would be quicksort’s. A result the size of its own noise is the page on this collection about reporting a difference without its spread. The lesson here is sharper: of two algorithms in a comparison, one may need a spread and the other not.

A variance that wobbles with the logarithm

Merge sort’s variance was described above as about 0.31n0.31\,n. Computed exactly at many sizes, it is not a constant times nn.

Merge sort's variance is 0.307 n at every power of two and bulges to 0.364 n between themThe exact variance of merge sort's comparison count divided by the number of keys, at 193 sizes spaced evenly on a doubling scale from 4,096 to 65,536. At every power of two it is 0.307, 0.307, 0.307, 0.307, 0.307; between them it rises to 0.364 at 43,740 keys, 0.42 of the way from one power of two to the next, and falls back. The same curve repeats in every doubling, so the variance is n times a periodic function of log₂ n rather than a constant times n. The mean does the same: n log₂ n minus between 1.240 n and 1.264 n.0.3200.3400.360keys sorted, on a doubling scalevariance of the count ÷ keys4,0968,19216,38432,76865,5360.364 n at 43,740exact, merge by merge193 sizes
Fig. 8 The exact variance of merge sort’s comparison count divided by the number of keys, at 193 sizes spaced evenly on a doubling scale from 4,096 to 65,536. At every power of two it is 0.307. Between them it rises to 0.364 at 43,740 keys, 0.42 of the way from one power of two to the next, and falls back — the same arch in every doubling. The mean behaves the same way: n log₂ n minus between 1.240 n and 1.264 n.

At every power of two the variance is 0.307n0.307\,n. Between powers of two it rises by almost a fifth and comes back, and the arch repeats exactly in every doubling. The variance is nn times a periodic function of log2n\log_2 n, not nn times a constant.

The cause is the split. When nn is a power of two every merge is perfectly balanced, 2k2^k against 2k2^k. Between powers of two the top-down split produces merges of unequal sizes at some levels — 21,870 against 21,870 at the top, but runs of different lengths lower down — and an unbalanced merge’s leftover has a different distribution from a balanced one’s. How many levels are unbalanced, and how badly, depends on where nn sits between powers of two and on nothing else, so the pattern repeats in every doubling. Flajolet and Golin worked out the same oscillation analytically, as a periodic function with a Fourier series; the plate is that function, drawn from counts.

The mean has the same wobble, and it has consequences for anybody fitting a curve to merge sort. Fitting a class to measurements granted merge sort its nlognn \log n class by fitting counts across three orders of magnitude, and the fit holds. But the second term is not a constant times nn. It is between 1.240n-1.240\,n and 1.264n-1.264\,n depending on where the size falls, so a fit of anlogn+bna\, n \log n + b\, n to sizes that happen to be powers of two will find a different bb from a fit to sizes that happen not to be. Neither is wrong. They are two readings of one periodic function, taken at different points in its period.

The worst case as a place nothing visits

Merge sort’s worst case is the number most often quoted about it: at most nlog2n2log2n+1n\lceil\log_2 n\rceil - 2^{\lceil\log_2 n\rceil} + 1 comparisons, which at 65,536 keys is 983,041. It is reached when every merge leaves exactly one key over. The best case, 524,288, comes when every merge takes one side whole before touching the other.

Merge sort on 65,536 keys can make anything from 524,288 to 983,041 comparisons, and all but two in ten thousand runs land in a window 1,055 wideThe whole range of comparison counts top-down merge sort can make on 65,536 distinct keys, from its best case of 524,288 (every merge takes one side entire before the other) to its worst of 983,041 (every merge leaves exactly one key over), drawn to scale. The dark band is where the count lands on random input with probability 0.9998: 965,177 to 966,232, which is 0.23% of the range. The mean is 965707.7. The worst case is 17,333 comparisons above it, 122.1 standard deviations, and a random input reaches it with probability 10^-7,189.every merge takes one side wholebest 524,288every merge leaves one key overworst 983,04199.98% of random inputs: 965,177 to 966,232n = 65,536, to scaleworst case 122.1 sd above the mean
Fig. 9 The whole range of comparison counts merge sort can make on 65,536 distinct keys, from its best case of 524,288 to its worst of 983,041, drawn to scale. The dark band is where the count lands on random input with probability 0.9998: 965,177 to 966,232, which is 0.23% of the range. The worst case sits 17,333 comparisons above the mean, 122 standard deviations, and a random input reaches it with probability about one in 10^7,189.

On random input the count lives in a band a thousand comparisons wide, inside a range of 458,753. The worst case is 17,333 comparisons above the mean. That is only 1.8% of the mean, and it is 122 standard deviations. The probability that a random input produces it is the product of every merge’s chance of leaving exactly one key over, which is about 10718910^{-7189}.

None of that makes the worst case unreachable. Merge sort is deterministic, and its distribution is over inputs, not over anything it chooses. An input built to make every merge leave one key over produces 983,041 comparisons every time it is sorted. The worst case found by climbing found merge sort’s worst case at sixty-four keys on every attempt, by local search. The band on the plate is a statement about random input, and it says nothing about an adversary.

This is the respect in which the two distributions on this page are not the same kind of object. Quicksort’s spread is its own: on any fixed input its random pivot gives the same distribution, so no adversary can remove it, and no benchmark can avoid it. That is the bargain what randomising the pivot buys described. Merge sort’s spread belongs to the input. On any one fixed input merge sort has no spread at all, and the sort whose count has no distribution — Batcher’s network, which ignores the input entirely — is the extreme of the same idea. What merge sort offers is not a guarantee against bad luck. It offers something benchmarks rarely get: on inputs drawn at random, the count is a constant to within a fifth of a per cent from a thousand keys up, and one measurement is enough.

Still open: the spreads of the sorts whose pieces are not independent

Merge sort’s spread came out small because its randomness split into independent pieces, and that independence is a special property of a merge on a random permutation. The same question can be asked of every other deterministic sort here, and for most of them the pieces are not independent.

Insertion sort is the easy case and makes a sharp prediction. Its comparison count is the number of inversions plus a correction of at most n1n - 1, and the distribution of inversions over random permutations is known exactly. Its generating function is the product of 1+x++xk11 + x + \cdots + x^{k-1} over kk up to nn, which is again a sum of independent pieces, one per key. So its variance should sit within a few per cent of n(n1)(2n+5)/72n(n-1)(2n+5)/72, the variance of the inversions, and its spread should grow as n3/2n^{3/2} against a mean growing as n2n^2 — a coefficient of variation falling as 1/n1/\sqrt{n}, faster than quicksort’s and slower than merge sort’s.

Heapsort is the interesting one. Its comparisons are spent in sift-down paths whose lengths depend on the heap’s current shape, and the shape after each extraction depends on every extraction before it. There is no decomposition into independent pieces, and no closed form is known to this collection. The measurement that follows computes the distribution exactly at small sizes by enumerating every input, samples it at large ones, and fits the growth exponent of the standard deviation. The prediction to test is that heapsort’s spread grows as n\sqrt{n} like merge sort’s, because its dependence is local. If it grows faster, then the dependence between extractions is carrying randomness over long distances. That would mean a heap remembers the order of its input for longer than its construction suggests.

Named alongside this one

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

The objects this essay names

Each one links to every other essay that touches it.

BenchmarkingComparison countDistributionExpected valueGeometric distributionMeasurement designMerge sortQuicksortReproducibilitySamplingVarianceWorst case