← The Ledger
Vol. I, No. 17 · Merge Structures

The Tournament Tree

A fixed bracket over k input streams that replays only the path the winner left behind.

Written by Khushal Agrawal

loading…

The Winner Tree

A tournament tree is a complete binary tree over k fixed leaf slots. Each leaf holds the current candidate from one input; each internal node holds the winner of the match between its two children. The root holds the overall winner, so reading the minimum of k streams costs O(1).

Building from k filled leaves costs k − 1 comparisons, one per internal node, which is optimal for finding a minimum. Like a binary heap the tree is complete and lives in an array; unlike a heap the leaf set is fixed, and internal nodes hold references to leaves rather than elements of their own.

The Array Layout

Nothing is allocated per node. The k run heads live in one array, the k − 1 internal nodes in another, and the tree structure is index arithmetic.

key[0 .. k-1]      // current head of each run
loser[1 .. k-1]    // internal nodes: index of the losing run
loser[0]           // the overall winner, sitting above the root

// the internal node directly above leaf s
parent(s) = (s + k) / 2
// and from any internal node, upward
parent(p) = p / 2

Leaf s and internal node p are both plain integers, so an ascent is a loop that halves an index. The tree never changes shape, so these positions are fixed for the life of the merge — which is what makes the access pattern predictable enough to stay in cache.

Replaying One Path

The structure earns its keep on the update. When the winner is consumed its source supplies a replacement into that same leaf, and only the matches on the path from that leaf to the root can change outcome — every other match involved neither the departing element nor the arriving one.

Replaying that path is ⌈log₂ k⌉ matches. No other node is read or written and the shape never changes, so an update touches a fixed set of array positions determined by the leaf index. The tree stays exactly 2k − 1 nodes however much data flows through it.

The Loser Tree

Replaying a match in a winner tree needs both children, because the node holds one contender and the other must be fetched from the sibling subtree. Demuth's 1956 refinement stores at each internal node the loser of that match instead, and keeps the overall winner in loser[0] above the root.

Now the ascent carries the current winner in a register and compares it against one stored value per level. Each level is one comparison and one read. The comparison count is unchanged at ⌈log₂ k⌉, but memory traffic halves — which is why external sorting implementations use loser trees rather than winner trees.

The Replacement Walk

This is the operation the whole structure exists for. Run s has a new head key; carry it upward, and at each level keep whichever of the two is smaller.

void replay(int s) {
    int winner = s;
    for (int p = (s + k) / 2; p >= 1; p /= 2) {
        if (less(key[loser[p]], key[winner])) {
            int t     = loser[p];   // the stored loser actually wins
            loser[p]  = winner;     // so the incumbent stays here
            winner    = t;          // and the winner ascends
        }
    }
    loser[0] = winner;              // overall winner, above the root
}

The swap is the whole idea: a node always ends up holding the loser of its match, so the invariant is restored level by level as the ascent proceeds. One comparison, one read, one conditional swap per level.

Building The Tree

Construction is the same walk run once per leaf, with the internal nodes seeded by a virtual run that wins every comparison.

for (int p = 1; p < k; p++) loser[p] = VIRTUAL;   // key -infinity
for (int s = k - 1; s >= 0; s--) replay(s);

Because VIRTUAL wins, the first real run to reach a node displaces itself into it as the loser and the virtual run continues upward — so each replay parks one real run at each level it passes. After all k replays every internal node holds a real loser and loser[0] holds the true winner. The cost is k − 1 comparisons in total, matching the lower bound for finding a minimum.

K-Way Merge

With replay in hand the merge is a six-line loop: emit the winner, refill its leaf, replay that path.

build();
while (key[loser[0]] != SENTINEL) {
    int s = loser[0];               // the winning run
    emit(key[s]);
    key[s] = next_from_run(s);      // SENTINEL when the run drains
    replay(s);
}

Each of the n output elements costs ⌈log₂ k⌉ comparisons, so the merge is O(n log k). Repeated two-way merging does the same number of comparisons but passes over the data log₂ k times; the tournament tree does it in one sequential scan of each run with O(k) resident state. That is the merge step behind external sorting and LSM tree compaction.

Comparison Count Against A Heap

A binary heap of k run heads solves the same problem, and the difference is visible in the inner loop. A heap sifts down from the root, and each level costs two comparisons: one to pick the smaller child, one to test the sifted value against it.

// heap: descending, the opponent is unknown
child = (key[l] < key[r]) ? l : r;    // comparison 1
if (key[v] <= key[child]) break;      // comparison 2

// loser tree: ascending, the opponent is already stored
if (less(key[loser[p]], key[winner])) swap;   // comparison 1

An ascent knows its opponent, so it needs one comparison per level rather than two. For a 1,000-way merge that is roughly 10 comparisons per record against 20; on long string or multi-column keys, that ratio is the ratio of merge times. The heap's advantage is that k may change at will.

Replacement Selection

The same tree generates the runs it later merges. Fill it with M records, then repeatedly emit the winner and read one new record into its leaf. A record whose key is below the one just emitted cannot go out in sorted order now, so it is tagged for the next run and made to lose every match in this one.

key[s] = read_next();
run[s] = (key[s] >= last_emitted) ? current_run : current_run + 1;

// compare (run, key) lexicographically, so next-run records
// lose every match while the current run is still draining
less(a, b) = run[a] != run[b] ? run[a] < run[b] : key[a] < key[b];

The run ends when every leaf carries the next-run tag. Because records arriving after the current output position stay usable, runs grow past the memory holding them: for random input the expected length is 2M rather than M, which halves the run count the merge phase must handle.

Selecting The Second-Smallest

The tournament also answers a selection question. Finding the smallest of n elements takes n − 1 comparisons, and the second-smallest must have lost exactly one match — its only loss was to the winner. The candidates are therefore the ⌈log₂ n⌉ elements that met the winner on its path, not all n − 1 losers.

A second tournament among those gives the second-smallest in n + ⌈log₂ n⌉ − 2 comparisons, which Kislitsyn proved optimal. The record of who lost to whom is information the tournament produces for free and a heap discards.

Sentinels And Ties

An exhausted run has nothing to supply, and the tree cannot shrink — removing a leaf would change the shape and invalidate every index. The standard treatment writes a sentinel key that loses every comparison, so the leaf stays and the arithmetic never changes. The merge stops when the winner itself is a sentinel, meaning every run is drained.

Ties need equal care. Comparing on the key alone leaves the winner ambiguous between two runs holding equal keys, so a merge that must be stable breaks ties by run number with lower-numbered runs winning — the same lexicographic comparator replacement selection already uses for its run tags.

Cache Behaviour

Internal nodes usually store a run index plus a cached copy of that run's current key. The cache costs one key per node and saves a dereference on every comparison, which matters when records are large or paged in from disk.

The access pattern is one fixed root-to-leaf path per output element, so the top levels of the array stay resident and only the deep nodes miss. The working set for a merge is the tree plus one input buffer per run — not the runs themselves — so k is bounded in practice by how many buffers fit in memory rather than by anything about the tree.

Engineering Trade-offs

A tournament tree gives one comparison per level instead of two, a fixed 2k − 1 node footprint, no allocation after construction, and a completely predictable access pattern. For merging a known number of sorted streams it does strictly less work than a heap.

It is also less general. The leaf count is fixed at build time, so admitting a new stream means rebuilding; there is no decrease-key, no meld, no removal of an arbitrary element. Exhausted inputs must be padded with sentinels rather than dropped, so a merge with many short runs keeps paying for dead leaves. Dynamic workloads want a priority queue; mergeable ones want a pairing heap.

Applications

Database sort operators are the documented home of the structure. Graefe's survey of sorting in database systems specifies the tree-of-losers priority queue for both phases of external merge sort — run generation by replacement selection and the merge itself — on the grounds that it reaches a new winner in log₂ N comparisons. IBM has patented hardware sort accelerators built directly on the tournament tree, including designs that stream keys through a tree backed by external memory.

Where systems merge sorted runs without one, they use a heap for the same job, which makes the comparison concrete: RocksDB's MergingIterator keeps one child iterator per memtable and SST file in a binary heap keyed on current key, and PostgreSQL's tuplesort.c merges external run tapes through a heap of tape heads. Both perform the two-comparisons-per-level descent that a loser tree avoids.

Summary

A tournament tree is a complete binary tree over a fixed set of k inputs that caches the outcome of every match. Consuming the winner and refilling its leaf invalidates only one root-to-leaf path, so the next winner emerges in ⌈log₂ k⌉ comparisons. Storing losers rather than winners lets the ascent carry its contender in a register, halving memory traffic.

Merging n elements from k runs costs O(n log k) with 2k − 1 nodes of state, and replacement selection uses the same walk to produce runs averaging twice the size of memory. The structure cannot resize, meld, or delete: it trades every dynamic operation for the cheapest repeated selection over a fixed set of streams.

The Tournament Tree: A fixed bracket over k input streams that replays only the path the winner left behind
The Tournament Tree — A fixed bracket over k input streams that replays only the path the winner left behind.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Demuth, H. B. (1985). Electronic Data Sorting. IEEE Transactions on Computers, C-34(4), 296–310. (Reprint of the 1956 Stanford PhD thesis introducing the tree of losers.) doi.org/10.1109/TC.1985.5009380
  2. Knuth, D. E. (1998). The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., §5.4.1 (replacement selection and trees of losers). Addison-Wesley. www-cs-faculty.stanford.edu/~knuth/taocp.html
  3. Kislitsyn, S. S. (1964). On the selection of the k-th element of an ordered set by pairwise comparisons. Sibirskii Matematicheskii Zhurnal, 5, 557–564. www.mathnet.ru/eng/smj5195

Applications and implementations

  1. Graefe, G. (2006). Implementing sorting in database systems. ACM Computing Surveys, 38(3), 10. doi.org/10.1145/1132960.1132964
  2. Larson, P.-Å. & Graefe, G. (1998). Memory management during run generation in external sorting. Proceedings of the 1998 ACM SIGMOD International Conference on Management of Data, 472–483. doi.org/10.1145/276304.276346
  3. IBM. Hardware implementation of a tournament tree sort algorithm using an external memory. US Patent 11,023,204 B2. patents.google.com/patent/US11023204/en
  4. Facebook. RocksDB: table/merging_iterator.cc. github.com/facebook/rocksdb/blob/main/table/merging_iterator.cc
  5. PostgreSQL Global Development Group. src/backend/utils/sort/tuplesort.c. github.com/postgres/postgres/blob/master/src/backend/utils/sort/tuplesort.c

Enjoyed this chapter? Support The Ledger.