Proofs: Tournament sort
These are the human proofs of Tournament sort, at full length.
Tournament sort outputs the items in stable sorted order full
This proof shows: correctness.
We order the indices by the strict order when , or when neither nor and . This is a total order on the indices, and listing the items in order is the stable sorted order.
For a node of the tree, let be the set of indices that are still in the leaves of the subtree of . We write for its least element in , or empty if is empty.
Lemma 1 (WINNER). If and , then WINNER.
Proof. is the union of and , so its least element is the less of the two minima, or the one that exists. If one slot is empty, WINNER returns the other. If both are full, with from the left subtree and from the right, then as indices, because the leaves of the left subtree hold smaller indices. WINNER returns only if , which is exactly in this case.
Invariant (I). For each internal node , ; each leaf holds its index or is empty.
After line L2. The leaves are right by line L1. Line L2 visits the internal nodes from down to 1, so both children of are done before . By Lemma 1, each is right.
After lines L5 to L7. Emptying leaf changes only for the ancestors of that leaf. Line L7 recomputes them from the parent of the leaf up to the root, so each one is recomputed after its children, which are right: the child on the path was just recomputed, and the other child has an unchanged subtree. By Lemma 1, (I) holds again.
Theorem. After TOURNAMENT-SORT, the array holds the input items in stable sorted order.
Proof. By (I), at step of line L3 the root holds , the -least index of the items not yet output. So is the item with the -th index in order. After steps, lists all items in order, which is the stable sorted order, and line L8 copies it into .
Termination and count. Each step empties one leaf, so the tree is empty after steps. The loop of line L6 runs times per step. Line L2 makes a comparison at a node only when both children are full; each comparison removes one index from the set of candidates for the root, so line L2 makes exactly comparisons when .