The floors

The floor a merge cannot reach

Merging two sorted lists of five keys each has 252 possible outcomes, so counting says eight comparisons might do. Solving the game says nine are needed, and on equal lengths the shortfall keeps growing, as half the logarithm of the length. Averaged over random inputs, though, the same count is missed by a tenth of a comparison. The counting floor is nearly exact on average and wrong in the worst case.

Every floor in this field so far has come from counting outcomes. The floor under every comparison sort counts n!n! orderings and takes the logarithm. It then shows that merge sort sits a couple of per cent above it, and that nothing can sit below.

How close anything gets to the floor took the argument apart one merge at a time. A merge of a pp-key run with a qq-key run has (p+qp)\binom{p+q}{p} possible interleavings, the logarithms of those counts add up to log2(n!)\log_2(n!), and so each merge has a floor of its own. It measured merge sort against those per-merge floors and found the waste spread across the tree, 4.076 comparisons in the largest merge and nothing at all in the smallest.

That measurement left a question it could not ask. Is a merge’s own floor something a merge can actually reach? The count says log2(m+nm)\lceil \log_2 \binom{m+n}{m} \rceil comparisons are necessary. It does not say they are enough. For sorting, nothing closes the gap in general. For merging, the whole game is small enough to solve.

Solving the merge

An algorithm merging a sorted list aa of mm keys into a sorted list bb of nn keys needs one fact about each aia_i: how many keys of bb are smaller. Call it pip_i. Because both lists are sorted, p1p2pmp_1 \le p_2 \le \dots \le p_m, and each such sequence is one interleaving.

Whatever an algorithm has learned can be written as a range for each pip_i. Comparing aia_i with bjb_j cuts that range at jj, and the cut spreads: if aia_i is below bjb_j then so is every earlier key of aa, and if it is above then so is every later one. A state of knowledge is two sequences of bounds. The fewest comparisons that still guarantee the answer from a state is one more than the best question’s worse outcome, the same minimax every pair must be asked used for graphs, and it is computed over every reachable state. At seven keys a list that is 2,760,615 states. A second solver checks the first at small sizes. It works on explicit sets of the interleavings still possible and shares no representation with the first, and the two agree.

Merging m sorted keys into n: the exact optimum meets the counting floor in 13 of 21 cases and misses it by one in 8A triangle of cells, one for each pair of list lengths m ≤ n up to 6. Each cell gives the exact fewest comparisons that merge the two lists on their worst interleaving, found by solving the game, above the counting floor ⌈log₂ C(m + n, m)⌉. 1 into 1: 1 against 1; 1 into 2: 2 against 2; 1 into 3: 2 against 2; 1 into 4: 3 against 3; 1 into 5: 3 against 3; 1 into 6: 3 against 3; 2 into 2: 3 against 3; 2 into 3: 4 against 4; 2 into 4: 5 against 4; 2 into 5: 5 against 5; 2 into 6: 6 against 5; 3 into 3: 5 against 5; 3 into 4: 6 against 6; 3 into 5: 7 against 6; 3 into 6: 7 against 7; 4 into 4: 7 against 7; 4 into 5: 8 against 7; 4 into 6: 9 against 8; 5 into 5: 9 against 8; 5 into 6: 10 against 9; 6 into 6: 11 against 10. Shaded cells are where the floor cannot be reached: 2 into 4, 2 into 6, 3 into 5, 4 into 5, 4 into 6, 5 into 5, 5 into 6, 6 into 6. The first row, a single key, always meets it, and the diagonal stops meeting it at five keys each.length of the longer list, nshorter, m1234561234561floor 12floor 22floor 23floor 33floor 33floor 33floor 34floor 45floor 45floor 56floor 55floor 56floor 67floor 67floor 77floor 78floor 79floor 89floor 810floor 911floor 10the optimum is one above the floorthe floor is reachedevery cell solved exactly · m ≤ n ≤ 6large: the optimum · small: ⌈log₂ C(m+n, m)⌉
Fig. 1 Each cell is a pair of list lengths, m keys merged into n, with m ≤ n ≤ 6. The large number is the exact fewest comparisons that merge them on their worst interleaving, found by solving the game. The small number is the counting floor. The two agree in 13 of the 21 cells and differ by one in 8: two into four, two into six, three into five, four into five, four into six, five into five, five into six and six into six.

The first row is binary search. Placing one key among nn takes log2(n+1)\lceil \log_2(n+1) \rceil comparisons and the floor is the same number, because the n+1n+1 positions are the outcomes and a binary search halves them each time. A single key can always be merged at the floor.

The second row already misses. Two keys into four sorted keys have (62)=15\binom{6}{2} = 15 interleavings, and four comparisons could tell sixteen apart. The solve needs five. At six the same happens again, 28 interleavings and a floor of five against six needed. The whole second row matches a closed form for two keys, published in the early 1970s. That formula is checked against the solve at every nn from 2 to 10, as a check on the solver rather than on the formula.

Fifteen outcomes and no even question

The smallest miss shows what goes wrong in all of them. Two keys into four have fifteen interleavings. Four comparisons can tell sixteen outcomes apart, but only if the first one leaves at most eight on each side, the second at most four, and so on down. So the question is whether any first comparison divides the fifteen that evenly.

None does. There are eight possible first comparisons, each key of aa against each key of bb, and they divide the fifteen interleavings as 5 and 10, 9 and 6, 12 and 3, 14 and 1, 1 and 14, 3 and 12, 6 and 9, and 10 and 5. The most even leaves nine on one side. Nine outcomes need four more comparisons, so every first choice ends at five.

The splits are uneven because of what a comparison between aia_i and bjb_j asks. It asks whether pip_i is below jj, and the number of interleavings on each side of that cut is fixed by how many ways the other key can sit around it. A key near the end of one list against a key near the start of the other is nearly always decided in one direction. A key in the middle against a key in the middle comes closest to even, and with two keys and four positions the closest available is nine to six. Counting assumes a question that cuts the outcomes in half. The list structure offers only the cuts that the positions allow.

The misses spread with size. Up to six keys a list, every case with both lists at four or more keys except four into four misses by one, and the diagonal stops meeting the floor at five keys each. The counting floor is a floor. It is not the answer, and the gap is structural. Counting treats every comparison as able to split the remaining outcomes in half. A comparison between two particular keys usually cannot.

Why equal lengths are the worst

On the diagonal the solver finds 1,3,5,7,9,11,131, 3, 5, 7, 9, 11, 13: exactly 2m12m - 1 at every size it reaches. That is also what the textbook merge makes on its worst input, the one that walks both lists to the end. The obvious algorithm is exactly optimal on equal lengths, and the counting floor is what fails to see it.

The reason is short enough to draw.

Why 9 comparisons are forced on two lists of 5: every adjacent pair of the merged output comes from different listsTwo sorted lists of 5 keys, a above and b below, whose merged order alternates a1 < b1 < a2 < b2 < … < a5 < b5. Each of the 9 adjacent pairs in that order, drawn as a line, has one key from each list, and swapping the two keys of any one pair gives another valid pair of sorted lists that agrees with every other comparison. An algorithm that never compared that pair cannot tell the two inputs apart and must be wrong on one, so every correct merge makes all 9 comparisons on this input. The counting floor for 5 and 5 is 8.aba1b1a2b2a3b3a4b4a5b5123456789left to right: the merged orderm = 5 · 9 forced comparisonscounting floor 8
Fig. 2 Two sorted lists of five keys whose merged order alternates, a1 < b1 < a2 < … < a5 < b5. Each of the nine adjacent pairs in that order has one key from each list. Swapping the two keys of any one pair gives another pair of sorted lists that agrees with every other comparison, so an algorithm that skipped that pair cannot tell the two inputs apart. All nine comparisons are forced, against a counting floor of eight.

That is an adversary argument, the kind the adversary who hides the edge used for connectivity: no counting, just an input on which any skipped question leaves two answers standing. It works for every mm, so 2m12m - 1 is proved at every size, not only at the sizes the solver reaches. The solver is checking the argument, and it agrees at all seven sizes it can reach.

What counting predicts for the same input is log2(2mm)\log_2 \binom{2m}{m}. By Stirling’s approximation, (2mm)\binom{2m}{m} is close to 4m/πm4^m / \sqrt{\pi m}, so the floor is 2m12log2(πm)2m - \tfrac12 \log_2(\pi m) plus a vanishing correction. The adversary demands 2m12m - 1. The difference grows.

Merging two lists of equal length costs 2m − 1 comparisons, and the counting floor falls further short as m grows: 1.26 at 7, 5.83 at 4,096How far the worst-case cost of merging two sorted lists of m keys each sits above the counting floor log₂ C(2m, m). The dots at m = 1 to 7 are exact solves of the game, each finding 2m − 1: gaps of 0.000, 0.415, 0.678, 0.871, 1.023, 1.148, 1.255. The line continues the same quantity to m = 4,096 using 2m − 1, which beyond 7 is the adversary argument rather than a solve: 1: 0.00, 2: 0.42, 4: 0.87, 8: 1.35, 16: 1.84, 32: 2.33, 64: 2.83, 128: 3.33, 256: 3.83, 512: 4.33, 1024: 4.83, 2048: 5.33, 4096: 5.83. It tracks ½log₂(πm) − 1 to within 0.000 at the right edge. The horizontal axis doubles at each step.0246keys in each list, mcomparisons above the counting floor2m − 1, provedby the adversarysolved exactly to m = 71416642561,0244,096m doubles at each stepgap ≈ ½log₂(πm) − 1
Fig. 3 How far 2m − 1 sits above the counting floor log₂ C(2m, m) as the lists grow, m doubling at each step. The dots at m = 1 to 7 are exact solves of the merge game: 0, 0.415, 0.678, 0.871, 1.023, 1.148 and 1.255. The dashed line continues the proved value, 2m − 1, out to 4,096 keys a list, where the gap reaches 5.83 comparisons and matches ½log₂(πm) − 1 to three decimals.

The gap is small in absolute terms: five comparisons out of eight thousand at 4,096 keys a list. It is also unbounded, and its shape is the interesting part. A logarithmic floor that is off by a logarithm of the length means counting has misjudged something basic about the problem. It has. It counts the outcomes but not how evenly a single comparison can divide them. When the lists interleave closely, a comparison near the middle of one list mostly confirms what the neighbouring comparisons already implied. The questions a sort asks twice found the same kind of comparison inside insertion sort: a question that is new, and still worth far less than a bit.

Four merges against the solved optimum

With the exact optimum known, real merges can be scored against it rather than against a floor that may be out of reach. Four are measured on every interleaving at five sizes, with every output checked sorted.

The textbook merge compares the two heads and emits the smaller. Binary insertion places each key of the shorter list by binary search, starting where the previous key went. Galloping probes ahead in steps of one, two, four and so on, then binary-searches the bracket it finds, which is the move when galloping pays measured inside a library sort. Hwang and Lin’s method, from 1972, compares the shorter list’s last key against a key 2t2^t from the end of the longer list, with t=log2(n/m)t = \lfloor \log_2(n/m) \rfloor. That discards 2t2^t keys with one question, or places the key with tt more.

On their worst interleavings, no simple merge is optimal everywhere: the textbook merge wins on equal lengths and loses on unequal onesWorst-case comparisons of four merges over every interleaving, against the exact optimum (solid rule) and the counting floor (dashed rule). 2 into 8: optimum 6, floor 6; the textbook merge 9, binary insertion 8, galloping 10, Hwang and Lin 7. 3 into 9: optimum 9, floor 8; the textbook merge 11, binary insertion 12, galloping 13, Hwang and Lin 9. 4 into 4: optimum 7, floor 7; the textbook merge 7, binary insertion 12, galloping 8, Hwang and Lin 7. 5 into 5: optimum 9, floor 8; the textbook merge 9, binary insertion 15, galloping 10, Hwang and Lin 9. 2 into 12: optimum 7, floor 7; the textbook merge 13, binary insertion 8, galloping 12, Hwang and Lin 8. Every run's output was checked sorted.2 into 845 interleavingsthe textbook merge9binary insertion8galloping10Hwang and Lin73 into 9220 interleavingsthe textbook merge11binary insertion12galloping13Hwang and Lin94 into 470 interleavingsthe textbook merge7binary insertion12galloping8Hwang and Lin75 into 5252 interleavingsthe textbook merge9binary insertion15galloping10Hwang and Lin92 into 1291 interleavingsthe textbook merge13binary insertion8galloping12Hwang and Lin8worst case over every interleaving · dark: equals the optimumsolid: optimum · dashed: counting floor
Fig. 4 Worst-case comparisons over every interleaving for four merges at five sizes, with the exact optimum (solid rule) and the counting floor (dashed rule). Two into eight: optimum 6; textbook 9, insertion 8, galloping 10, Hwang and Lin 7. Three into nine: optimum 9; Hwang and Lin 9, the others 11 to 13. Four into four: optimum 7; textbook and Hwang and Lin 7. Five into five: optimum 9; textbook and Hwang and Lin 9, insertion 15. Two into twelve: optimum 7; insertion and Hwang and Lin 8, textbook 13.

Nothing is optimal everywhere, and the losses have different sources. The textbook merge is optimal on equal lengths and wastes six of thirteen comparisons at two into twelve. It asks about the long list one key at a time, when the answer is nearly always “keep going”. Binary insertion is the reverse. It is close at two into twelve and needs fifteen at five into five, because a binary search over what remains of bb does not know that the next key of aa is probably just past the previous one.

The two failures are mirror images, and each is a choice about which question to ask first. The textbook merge always compares the two heads, a question that splits the outcomes evenly only when the lists are the same length. Binary insertion always compares against the middle of what remains, which splits evenly only when the shorter list has a single key. Neither asks the question that the two lengths call for, and the grid above shows that asking the most even question available is still not enough to reach the floor.

Galloping sits between the two and is never the best of the four here. Its extra cost is the probing: to place a key dd positions away it spends about 2log2d2 \log_2 d comparisons where a search that knew dd would spend log2d\log_2 d. Hwang and Lin is optimal at three of the five sizes and one comparison over at the other two. It is the only one of the four that adjusts to the ratio of the two lengths, and it is the only one that is never badly wrong.

The average floor is nearly exact

Everything so far is about the worst interleaving. Merge sort’s per-merge accounting in how close anything gets to the floor was an average over random inputs, and the average has a floor too. Over uniformly random interleavings, no algorithm can average fewer than log2(m+nm)\log_2 \binom{m+n}{m} comparisons, the same count without the ceiling. The same solve can weight each state by how many interleavings it still allows and minimise the expected number of questions instead of the worst.

On average the counting floor is nearly reached: the best possible merge into 6 sits 0.05–0.11 comparisons above log₂ C at every lengthMerging m keys into 6, for m from 1 to 6. The counting floor log₂ C(m + 6, m) — 2.807, 4.807, 6.392, 7.714, 8.852, 9.852 — against the exact least expected number of comparisons over uniformly random interleavings — 2.857, 4.893, 6.500, 7.824, 8.963, 9.963 — and the exact worst case, 3, 6, 7, 9, 10, 11. The textbook merge's mean over every interleaving is 3.86, 5.71, 7.07, 8.23, 9.29, 10.29. The average optimum is never more than 0.111 above the floor, while the worst case is up to 1.29 above it.0510123456keys in the shorter list, merged into 6comparisonscounting floor, log₂ Cbest possible, on averagebest possible, worst casethe textbook merge, on averageevery interleaving · exactn = 6
Fig. 5 Merging one to six keys into six. The counting floor log₂ C(m + 6, m) is 2.807, 4.807, 6.392, 7.714, 8.852 and 9.852. The exact best possible average is 2.857, 4.893, 6.500, 7.824, 8.963 and 9.963, never more than 0.111 above it. The exact best worst case is 3, 6, 7, 9, 10 and 11, up to 1.29 above. The textbook merge averages 3.86 to 10.29 over every interleaving.

The average optimum lies within a tenth of a comparison of the counting floor at every length. The worst case, with the same lengths and the same floor, misses by up to 1.29. So the floor is nearly exact on average and it is the worst case that counting gets wrong. That is the opposite of what the ceiling on a worst-case floor would suggest.

The reason is the same uneven split. An algorithm cannot divide the remaining interleavings in half with one comparison, but it can come close, and an average forgives a question that splits 55 to 45. The worst case forgives nothing, since the adversary always takes the larger side. Over many questions a small imbalance becomes a whole comparison in the worst case and a tenth of one on average.

That also sorts the waste how close anything gets to the floor measured in merge sort into what could be avoided and what could not, width by width. That essay found merges of four keys wasting 0.078 comparisons each and merges of eight wasting 0.261, against the bits their interleavings carry. Solved exactly on equal halves, the numbers look like this:

  • Two and two. Floor 2.585, best possible average 2.667, textbook merge 2.667. The textbook merge is the best possible merge of that size, and all of its 0.082 excess is unavoidable.
  • Four and four. Floor 6.129, best 6.229, textbook 6.400. Of an excess of 0.271, 0.099 is unavoidable and the rest, 63%, belongs to the textbook merge.
  • Six and six. Floor 9.852, best 9.963, textbook 10.286. Of 0.434, 74% is recoverable.
  • Seven and seven. Floor 11.745, best 11.862, textbook 12.250. Of 0.505, 77% is recoverable.

The unavoidable part hardly moves, 0.08 to 0.12 across those sizes. The textbook merge’s own share grows with the merge. So the eleven per cent of merge sort’s excess that the earlier table put in its four-key merges could not be removed by any merge at all, and the share that could be removed grows with the width of the merge. The recovery would need a merge far more complicated than comparing two heads, which is one reason merge sorts do not attempt it.

A thousand to one

The exact solves stop at a few keys a list, and the ratio between the two lengths is where the four merges really differ. With 64 keys in the short list and random interleavings, the comparisons each merge makes can be set against the counting floor up to a long list of 65,536 keys.

Merging 64 keys into 64 to 65,536: each simple merge is near the floor at one end only, and Hwang and Lin stay within 3% of it throughoutMean comparisons divided by the counting floor log₂ C(m + n, m), for m = 64 and n from 64 to 65,536, over 32 seeded random interleavings at each size. The textbook merge: 1.018, 1.101, 1.393, 1.989, 3.073, 5.088, 8.671, 15.144, 26.971, 48.676, 88.772. Binary insertion: 2.607, 2.206, 1.944, 1.743, 1.614, 1.518, 1.447, 1.395, 1.351, 1.318, 1.289. Galloping: 1.079, 1.119, 1.200, 1.310, 1.406, 1.481, 1.543, 1.596, 1.636, 1.676, 1.707. Hwang and Lin: 1.003, 1.029, 1.021, 1.017, 1.015, 1.011, 1.011, 1.011, 1.009, 1.008, 1.007. The textbook merge is 1.018 times the floor on equal lengths and 88.8 times it when one list is 1024 times the other; binary insertion goes the other way. Both axes are logarithmic.11010010³125102050how many times longer the second list is, n / mcomparisons ÷ counting floorthe textbook mergebinary insertiongallopingHwang and Linm = 64 · 32 random interleavings a size1 is the floor
Fig. 6 Mean comparisons divided by the counting floor, merging 64 keys into lists 1 to 1,024 times as long, over 32 seeded random interleavings at each ratio. The textbook merge goes from 1.018 on equal lengths to 88.8 at a thousand to one. Binary insertion goes from 2.607 down to 1.289. Galloping rises from 1.079 to 1.707. Hwang and Lin stay between 1.003 and 1.029 at every ratio. Both axes are logarithmic.

The four curves say something the small grid could only hint at. The textbook merge is within 2% of the average floor on equal lengths and 89 times over it at a thousand to one. Binary insertion is 2.6 times over on equal lengths and drifts towards the floor as the ratio grows, reaching 1.29 at the right edge. Galloping starts near the floor and climbs towards a factor of two. That is the 2log2d2\log_2 d against log2d\log_2 d of its probing showing through, once the gaps between keys become the dominant cost.

Hwang and Lin stay within 3% of the floor at every ratio, and at 1.1% or less from sixty-four to one upwards. It is the algorithm that asks the question counting assumes: one that splits the remaining possibilities as evenly as the two lengths allow. Its first comparison is chosen by the ratio, and that choice is most of what separates it from the other three.

What the solve settles and what it leaves

Five things here are exact.

The worst-case optimum is computed for every pair of lengths up to six keys each and for equal lengths up to seven, and it agrees with a second solver that shares no representation. It reproduces log2(n+1)\lceil \log_2(n+1) \rceil for a single key and the published closed form for two keys. On equal lengths it finds 2m12m - 1 at every size it reaches, which the adversary argument proves at every size. The counting floor is missed in 8 of 21 cells, and the miss on equal lengths grows as 12log2(πm)1\tfrac12 \log_2(\pi m) - 1. The average optimum is within 0.111 comparisons of the counting floor at every length merged into six.

Three things are not settled.

The worst-case optimum between the edges. For lengths beyond the solver’s reach and ratios other than one, the exact optimum is known only in special cases. Hwang and Lin’s method is known to stay within about mm comparisons of the counting floor, and at the sizes solved here it is within one of the optimum. That is not a proof that it is within one everywhere.

The average at large sizes. A gap of 0.111 is measured at six into six. Whether the best average stays a bounded distance above the floor as lengths grow, or creeps up as the worst case does, is not something six keys can show. The ratio plate is an upper bound from one algorithm, not the optimum.

Merges inside a sort. Merge sort does not merge random interleavings independently. The runs at each level come from the level below, and an adaptive sort decides its merge order from the data. Two floors that can be added found that floors from different parts of a problem can add. Whether per-merge floors add into a floor for a whole sort that uses a different merge at each size is a separate question.

Still open: the merge that sorts ties

Every key here is distinct, and that is the assumption most worth dropping. The floor when the values repeat showed that repeated values lower the sorting floor by more than half, since equal keys need no relative order. A merge of two runs drawn from a few distinct values has far fewer outcomes than (m+nm)\binom{m+n}{m}. Keys of aa equal to a key of bb can go on either side, so the question is where the runs of equal values begin and end, not where each key goes.

The measurement that follows sets up the same game for lists over an alphabet of kk values. A state of knowledge is then a range for each boundary between value classes, not for each key. The solve at small sizes finds the exact worst-case and average optima as kk falls from m+nm + n to two. The prediction is that the counting floor is more wrong in the worst case with few values, not less. A comparison that comes out equal carries more information than either strict answer and is also rarer, so it is exactly the kind of question an adversary can refuse to give. If that holds, then the merges that treat equality as a third outcome, which most library merges do not, are the only ones that can approach the lower floor at all.

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.

Adversary argumentAverage caseBinary searchComparison countDecision treeExhaustive searchGallopingHonest limitInformation floorLower boundMerge sortWorst case