The floors

The merge that can say equal

When two sorted lists draw their keys from a few values, equal keys can go on either side of each other, so far fewer answers are needed and the counting floor falls. Merging four keys into four over four values needs only 27 answers, not 70, and the floor falls from seven comparisons to five. A merge whose comparisons answer only 'at most' still needs seven on its worst input, exactly as many as distinct keys, because it can never learn that two keys are equal. A merge whose comparisons can answer 'equal' needs five and meets the floor. Solved exactly over every input, the third answer is the whole difference, and on average it is worth more than an optimal strategy.

The floor a merge cannot reach solved the game of merging two sorted lists of distinct keys. A merge of mm keys into nn must be able to give (m+nm)\binom{m+n}{m} different answers, one for each way the lists can interleave, so counting says it needs at least ⌈log⁡2(m+nm)⌉\lceil\log_2\binom{m+n}{m}\rceil comparisons. Solving the game exactly — every state of knowledge, every possible comparison, the adversary’s best reply — found that counting is right up to four keys a list and one comparison short from five: 252 outcomes say eight comparisons, and the game needs nine.

Every key there was distinct, and its closing section named that as the assumption most worth dropping. The floor when the values repeat had shown that repeated values lower the floor under sorting by more than half, because equal keys need no relative order. A merge of two lists drawn from a few values should have far fewer outcomes in the same way: a key of the first list equal to a key of the second may go on either side of it. The section predicted that the counting floor would be 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 rarer, so it is exactly the kind of answer an adversary can decline to give. If that held, only merges that treat equality as a third outcome could approach the lower floor at all.

The game can be solved again with ties in it, and the answer divides along exactly the line the prediction drew. The division is sharper than predicted: whether the third answer exists matters more than anything else about the merge.

What an input is when keys can be equal

With repeated values, an input is no longer an interleaving. It is two sorted lists read as a sequence of value classes, each holding some keys of the first list and some of the second. Two lists of four keys over at most four values can be arranged 648 ways. A merge’s answer is still an interleaving, and an interleaving is correct for an input when every key of the first list sits among the keys of the second at a place its value allows.

One input of four keys each over four values, drawn as value classes: a key of the first list may go anywhere among the keys of the second that equal it, so each has a range of correct positions — here a1 after 0 to 1, a2 after 3 to 4, a3 after 3 to 4, a4 after exactly 4 of the second list's keysTwo sorted lists, a1 to a4 and b1 to b4, laid out by value: value 1 holds 1 of the first list and 1 of the second; value 2 holds 0 of the first list and 2 of the second; value 3 holds 2 of the first list and 1 of the second; value 4 holds 1 of the first list and 0 of the second. For each key of the first list, the number of keys of the second list that may precede it in a correct merge: a1 from 0 to 1, a2 from 3 to 4, a3 from 3 to 4, a4 from 4 to 4. A merge is finished when one choice within every range is certain for every input still possible.value 1value 2value 3value 4first listsecond lista1b1b2b3a2a3b4a4a's rangea1a2a3a4one input, four valuesa range: where a key may go
Fig. 1 One input of four keys a list over four values: a1 and b1 share value 1, b2 and b3 hold value 2, a2, a3 and b4 share value 3, and a4 is alone at value 4. Each key of the first list may be preceded by a range of keys of the second: a1 by none or b1, a2 and a3 by three or four, a4 by exactly four.

Where distinct keys give each key of the first list one correct position, equal keys give it a range. In the input drawn, a1 equals b1 and may go before or after it; a2 and a3 equal b4 and may go on either side. A merge is finished when it knows enough to choose a position inside every range at once, for every input still consistent with what it has asked. The condition has a short form. For each key, take the largest lower end and the smallest upper end of its range over the inputs still possible. The merge is done when the first is never above the second, and then placing each key at the largest lower end is a correct answer for all of them.

That condition turns the game into something that can be solved exactly. A state is the set of inputs still consistent, kept as a bitset over the 648. A comparison splits the set by its answer, and memoised minimax over the splits gives the exact optimum. It is exact on the worst input and on average over lists whose keys are drawn uniformly from the kk values. The merge is taken to know kk, so the optimum found is a lower bound for any merge that does not.

Fewer answers than inputs

What ties do to the count of outcomes: with 4 values, two lists of 4 have 648 different orderings, but 27 interleavings are enough to answer all of them, against 70 for distinct keys — equal keys make many inputs share an answer, which is why the counting floor fallsFor two sorted lists of 4 keys over at most k values: the number of order types (inputs a comparison merge can tell apart, equalities included) and the fewest interleavings such that every input has a correct one among them, found by exact search. Inputs (order types): k 2 24, k 3 177, k 4 648, k 5 1,428, k 6 2,148, k 7 2,498, k 8 2,568. Answers needed: k 2 5, k 3 10, k 4 27, k 5 44, k 6 62, k 7 68, k 8 70. With distinct keys the two coincide at 70. The vertical axis is logarithmic; its ticks are 1, 10, 100 and 1,000.01232345678distinct values the keys may take (k)count (logarithmic)inputs (order types)answers needed70, distinct keys4 into 4tick labels are powers of ten
Fig. 2 For two lists of four keys over at most k values: the number of inputs a comparison merge can tell apart, and the fewest interleavings that give every input a correct answer. Inputs: 24 at two values, 648 at four, 2,568 at eight. Answers needed: 5, 27 and 70. With distinct keys both are 70.

The counting floor needs the number of different answers a merge must be able to give, and with ties that is not the number of inputs. Equal keys make one interleaving correct for many inputs, so the question is the fewest interleavings that cover every input, found by exact search. With four values, two lists of four have 648 inputs but 27 interleavings answer all of them, against 70 for distinct keys. The inputs grow with kk — there are more ways to arrange keys over more values — while the answers needed grow towards the distinct case, since with enough values ties become rare. The counting floor is the logarithm of the answers: three comparisons at two values, four at three, five at four, rising to seven with seven or eight values.

So the prediction’s first half is right before any game is solved. Repeated values lower the floor, and they lower it more than the number of inputs would suggest. The floor moves when the question does found that a floor is set by how many answers an algorithm must be able to give, not by how many inputs it might see, and ties are a case where the two part company.

The comparison that cannot say equal

Two games are solved. In the two-way game a comparison of aia_i with bjb_j answers “ai≤bja_i \le b_j” or not. That is what < or <= in merge code returns, with a tie sent to one side, and what the standard library merges ask. In the three-way game it answers less, equal or greater, which is what a comparator returning a sign reports.

Merging 4 keys into 4 when keys can be equal: with 4 distinct values the counting floor falls to 5 comparisons, a merge whose comparisons answer only ≤ still needs 7 on its worst input — exactly what distinct keys need — and one whose comparisons can answer "equal" needs 5The exact fewest comparisons that merge two sorted lists of 4 keys each on their worst input, when the keys take at most k distinct values, found by solving the game over every order type of the two lists. Two-way, solved: k 2 3, k 3 5, k 4 7, k 5 7, k 6 7, k 7 7, k 8 7. Three-way, solved: k 2 3, k 3 4, k 4 5, k 5 6, k 6 7, k 7 7, k 8 7. Counting floor: k 2 3, k 3 4, k 4 5, k 5 6, k 6 6, k 7 7, k 8 7. The counting floor is the base-two logarithm, rounded up, of the fewest interleavings that give every input a correct answer. With distinct keys the optimum is 7 (dotted).0123456782345678distinct values the keys may take (k)comparisons, worst casetwo-way, solvedthree-way, solvedcounting floordistinct keys4 into 4, every inputdotted: distinct keys
Fig. 3 The exact worst-case optimum for merging four keys into four over at most k values. Two-way: 3, 5, 7, 7, 7, 7, 7 for k from 2 to 8. Three-way: 3, 4, 5, 6, 7, 7, 7. Counting floor: 3, 4, 5, 6, 6, 7, 7. Distinct keys: 7.

With four values the counting floor is five comparisons. A two-way merge needs seven on its worst input — exactly what distinct keys need — and a three-way merge needs five. From four values up, the two-way merge gains nothing in the worst case from the ties. At two and three values it does gain, since there are too few values for the adversary to build a hard input, but from k=mk = m on it is back at the distinct-key optimum. The three-way merge follows the floor down. It meets it at two, three, four, five, seven and eight values, and misses it by one at six.

The reason is in what “ai≤bja_i \le b_j” can say. It is yes exactly when fewer than jj keys of the second list are strictly below aia_i. So everything a two-way merge can ever learn is, for each key of the first list, how many keys of the second lie strictly below it — the lower end of its range — and nothing about the upper end. A tie widens a key’s range upwards, and a two-way merge cannot see that the range is wide.

Ties also let few values produce many patterns of lower ends. Distinct keys give 70 patterns for four keys a list, one for each interleaving. With ties allowed, four values produce 69 of them: the pattern of an alternating interleaving, for instance, comes from pairing a1 with b1, a2 with b2 and so on at four values. With ties forbidden, four values produce only 26. So a two-way merge over four values faces nearly the whole distinct-key problem, and needs the distinct-key worst case. Solved on inputs without ties, the same two-way game over four values needs five comparisons, not seven. The adversary uses the ties, and the two-way merge cannot tell it is doing so. That is the shape of the argument the adversary who hides the edge used for graph connectivity: the adversary keeps every answer consistent with an input the algorithm cannot rule out, and here the input it cannot rule out is one with ties it cannot see.

A three-way comparison reads both ends of a range. “Less” says aia_i’s range ends before bjb_j, “greater” that it starts after, and “equal” that bjb_j lies inside it. The prediction pictured the equal answer as the valuable one, which an adversary would decline to give. What the three-way merge gains is more general: every answer, equal or not, now says where a range can end, and a merge only has to find one position inside each range.

On average, the third answer beats the best strategy

On average, with keys drawn uniformly from 4 values: the textbook merge makes 6.23 comparisons if it only asks ≤ and 4.69 if it takes both keys when they are equal; the best merges in each game make 5.60 and 4.20 — the third answer is worth more than solving the gameMean comparisons over lists of 4 keys whose values are drawn independently and uniformly from k, then sorted, computed exactly over every order type with its probability. Textbook, two-way: k 2 5.75, k 3 6.11, k 4 6.23, k 5 6.29, k 6 6.33, k 7 6.35, k 8 6.36. Solved, two-way: k 2 2.10, k 3 4.06, k 4 5.60, k 5 5.96, k 6 6.04, k 7 6.08, k 8 6.10. Textbook, three-way: k 2 4.00, k 3 4.41, k 4 4.69, k 5 4.90, k 6 5.06, k 7 5.19, k 8 5.30. Solved, three-way: k 2 2.10, k 3 3.32, k 4 4.20, k 5 4.59, k 6 4.88, k 7 5.04, k 8 5.16. The three-way textbook merge takes both keys and advances both lists when they compare equal.024682345678distinct values the keys may take (k)comparisons, averagetextbook, two-waysolved, two-waytextbook, three-waysolved, three-way4 into 4, uniform valuesdashed: the textbook merge
Fig. 4 Mean comparisons over lists of four keys drawn uniformly from k values. At k = 4: the textbook merge 6.23 two-way and 4.69 three-way, the solved optimum 5.60 two-way and 4.20 three-way. At k = 2: 5.75, 4.00, 2.10, 2.10. At k = 8: 6.36, 5.30, 6.10, 5.16.

The textbook merge is the loop every library merge is built from: compare the heads, take the smaller, repeat. Its three-way form takes both heads when they compare equal and advances both lists. With keys drawn uniformly from four values, the two-way textbook merge makes 6.23 comparisons on average and the three-way one 4.69. The best two-way merge of all, solved exactly, makes 5.60. The textbook loop with the third answer is better on average than the optimal strategy without it at every kk from four to eight; at eight values it is 5.30 against 6.10. At three values the optimal two-way strategy is still ahead, 4.06 against 4.41.

The three-way textbook merge is no cleverer than the two-way one; it uses an answer the other throws away. Every equal comparison places two keys at once, and with four values and eight keys equal heads are common. The solved optimum adds what cleverness can add on top: from 4.69 to 4.20 at four values, about half a comparison, against the one and a half the third answer is worth on its own.

At two values the solved games coincide at 2.10 comparisons, against 5.75 and 4.00 for the two textbook merges. With two values an input is two boundaries, one in each list, and a merge that searches for them rather than walking the lists needs only three comparisons at worst. When galloping pays measured Timsort’s merge switching to that kind of search when one list keeps winning, and with two values that is the whole of the problem.

Why libraries ask the two-way question

Every library merge measured in this collection asks the two-way question. The sort the library ships found Timsort in Python, Java, Rust and Android, introsort in C++, and dual-pivot quicksort for Java’s primitives. The interfaces they sort through all ask one thing of a pair of keys: whether the first is less than the second. C++'s std::merge takes a comparison that must be a strict weak ordering. Python’s sorted calls __lt__ and nothing else. Rust’s slice sort is written against is_less. None of them can be told that two keys are equal, because the question they ask has no such answer.

There are sound reasons for that. A strict weak ordering is the least a caller must supply, and it is enough for a sort to be correct. For distinct keys the two-way question loses nothing, and as ties become rare the solved games coincide in the worst case — from six values up at four keys a list. The cost falls on inputs with few values, and there it is the cost measured here: two comparisons in seven on the worst input at four keys a list and four values, and a quarter of the textbook merge’s average.

The three-way answer is usually available. A comparator that returns a sign computes it anyway, and one comparison of two integers or two strings costs the same whether the result is reported as a sign or as a boolean. So the saving is not bought with extra work per comparison. It is thrown away at the interface, by a function that computes three answers and reports two.

How far each game sits from the floor

How far each game sits above the counting floor: at 4 into 4 a two-way merge misses it by 0, 1, 2, 1, 1, 0, 0 comparisons as k runs from 2 to 8, most with a few values and none with distinct ones; a three-way merge misses it by 0, 0, 0, 0, 1, 0, 0 — never by more than oneThe exact worst-case optimum less the counting floor, for merges of 3 into 3 and 4 into 4 over at most k values. Two-way, 3 into 3: k 2 0, k 3 1, k 4 1, k 5 0, k 6 0. Three-way, 3 into 3: k 2 0, k 3 0, k 4 0, k 5 0, k 6 0. Two-way, 4 into 4: k 2 0, k 3 1, k 4 2, k 5 1, k 6 1, k 7 0, k 8 0. Three-way, 4 into 4: k 2 0, k 3 0, k 4 0, k 5 0, k 6 1, k 7 0, k 8 0. Dashed lines are 3 into 3.0122345678distinct values the keys may take (k)comparisons above the counting floortwo-way, 3 into 3three-way, 3 into 3two-way, 4 into 4three-way, 4 into 4worst case, every inputdashed: 3 into 3
Fig. 5 The exact worst-case optimum less the counting floor. Four into four, two-way: 0, 1, 2, 1, 1, 0, 0 for k from 2 to 8; three-way: 0, 0, 0, 0, 1, 0, 0. Three into three, two-way: 0, 1, 1, 0, 0 for k from 2 to 6; three-way: 0 at every k.

The counting floor is most wrong for the two-way merge with a few values, and least wrong with distinct keys: at four into four it misses by 0, 1, 2, 1, 1, 0 and 0 comparisons as kk runs from two to eight. The largest gap, two comparisons, is at k=4k = 4. There the floor has fallen furthest relative to what the two-way merge can use. The three-way merge misses the floor only at four into four with six values, by one; at three into three it meets it at every kk. The prediction said the floor would be more wrong in the worst case with few values, and for the merges that libraries ship, it is.

Five into five follows the same pattern where it can still be solved. With four values the floor is six comparisons, the three-way merge needs six, and the two-way merge needs eight, two above the floor and one below the nine that distinct keys need. At three values the floor is four and both games need five. That solve visits 428,199 sets of inputs in the three-way game, and five values take it past what an exact solve here can hold; that is where the table stops.

How close anything gets to the floor measured sorting algorithms against the counting floor and found merge sort within 2.2% of it. That was with distinct keys, where a merge’s two-way comparisons lose nothing. With repeated keys the same merge sort is measured against a floor it cannot see, because none of its comparisons ever reports a tie. The floor fell, and the algorithm’s cost did not.

What the solve does and does not cover

Small lists, exactly. Every number is exact, over every input, for lists of three, four and five keys. Nothing here says how the gap grows at larger sizes. The distinct-key page found its gap growing as half the logarithm of the length, and the equal-key gap may grow differently.

A merge that knows kk. The solved merges are told how many values there can be, which lets them stop as soon as the inputs still possible share an answer. A merge that does not know kk must assume the worst, so the optimum here is a lower bound for it. The textbook merges do not use kk at all, so their counts are what they are.

One question at a time, between the lists. Every comparison is between a key of one list and a key of the other, as in merging. Comparisons within a list tell a merge nothing it does not know from the lists being sorted, except whether neighbouring keys are equal. A three-way comparison of neighbours could reveal a run of equal values and is not in either game.

Uniform values, for the average. The averages draw each key uniformly from kk values. A skewed distribution makes ties among the common values more frequent and would widen the three-way advantage on average.

Ranges are what a merge may use; stability is what a library promises. A stable merge must put equal keys of the first list before those of the second. That removes the ranges, so a stable merge is solving the distinct-key problem whichever game it is in. The pattern that defeats the pattern found pdqsort handling a few distinct values with a partition scheme that groups equal keys, which is the same freedom used in a sort that makes no stability promise.

Still open: a merge that finds its runs of equal keys first

The three-way merge gains because every equal answer places a pair of keys at once. The gain grows with how many keys share a value, but it is taken only where one list’s head happens to meet an equal head in the other. A merge could look for runs of equal values deliberately. A three-way comparison between neighbours in one list says whether they are equal, and a run of equal keys, once found, can be placed against the other list with one search rather than one comparison a key.

The measurement that follows adds comparisons within a list to the three-way game and solves it again at the same sizes. It asks whether the worst case falls below the between-lists floor, and what the textbook-plus-runs merge — gallop over a run of equals before comparing across — costs on average against the solved one. The prediction is that within-list comparisons cannot help the worst case, since the adversary can make every neighbour distinct and within-list questions then tell a merge nothing it did not know. On average, with few values, they should help a great deal, since a run of rr equal keys costs about log⁡2r\log_2 r comparisons to find and saves up to rr. The question is where on kk the average saving stops paying for the questions that come out unequal. That crossing is the number of values below which a library should look for equal runs before merging, and pdqsort already makes a version of that choice for partitioning.

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.

Adversary argumentAverage caseComparison countDecision treeEqual elementsExhaustive searchHonest limitInformation floorLower boundMerge sortWorst case