Proofs: Tournament tree
These are the human proofs of Tournament tree, at full length.
The winner tree and the loser tree give the winner after each update full
This proof shows: correctness.
The slots are . Slot beats slot if , or and , with larger than every real key. This is a strict total order on slots, so every nonempty set of slots has a unique winner , which beats every other slot of . For a node of the tree, let be the set of slots whose leaves are below or at , and let . For an internal node , , a disjoint union, so
Lemma 1 (winner tree). If for each slot and is the winner of and for each internal , then for every node.
Proof. By induction on the height of . At a leaf , and . At an internal node, and by induction, and (1) gives .
BUILD. Line L1 sets the leaves. Line L2 visits in decreasing order, and both children are larger than , so they are set before . Line L3 then sets as Lemma 1 needs. So after BUILD, is the overall winner.
UPDATE in the winner tree. A change of changes only for the nodes with , which are the ancestors of leaf . Lines L4 to L7 visit these ancestors from the bottom up. When node is visited, its child on the path was visited before, and its other child is not an ancestor of the leaf, so both children satisfy the condition of Lemma 1. Line L6 then makes satisfy it. Nodes off the path are unchanged and still satisfy it. By Lemma 1, after the loop is the winner of the new keys.
Lemma 2 (loser tree, the path of the winner). Let the loser tree satisfy (L): is the loser of and for each internal , and . Let . Then for each internal ancestor of leaf , with its child on the path and the other child, and .
Proof. Slot is in and beats every slot of , so . At node , the two players are and , and wins, so the loser is .
LOSER-UPDATE. Let , and let the key of change; all other keys stay. Let be the internal ancestors of leaf from the bottom, and write for the child of on the path and for the other child. After the change, write for the new winners. Since does not contain , by Lemma 2.
We show by induction on the claim: when the loop reaches , the variable holds , and each for holds the new loser at . At , is the leaf of and . At step , the two players at are and . Line L11 keeps the loser in and puts the winner in , which by (1) is . This proves the claim for .
After the loop, every node on the path holds its new loser, , and line L13 stores it in . Nodes off the path have no slot below them, so their players and losers are unchanged. So (L) holds for the new keys, and is the new winner. Each visited node costs one comparison, so the update costs comparisons.
Merge. In the -way merge, slot holds the smallest key not yet output from run , or . The winner is the smallest of these, which is a smallest key not yet output of all runs, because each run is sorted. So each output is the next key in sorted order, the output stops when all slots hold , and every key is output once.