Proofs: Tournament method
These are the human proofs of Tournament method, at full length.
The tournament method returns the largest and the second largest full
This proof shows: correctness, termination.
Let be the items of in sorted order, with . The claim is: TOURNAMENT-SECOND stops and returns , after at most comparisons.
Termination and the shape of the rounds. A round on players makes matches and leaves players (lines L4 to L9). So the number of players drops in each round and the loop of line L2 stops with one player. A round never adds a player, and each match removes exactly one, the loser, so the tournament makes exactly matches, and each index other than the champion is the loser of exactly one match. Lines L11 and L12 scan a finite list, so the algorithm stops.
Lemma 1 (the beaten lists). If is appended to beaten in line L7, then , and is still a player after the round in which leaves.
Proof. Line L6 sets only if , and only if . In both cases . Line L7 appends to , the players of the next round.
Lemma 2 (the champion). , and for each index there is an index in beaten with .
Proof. Let . Then lost exactly one match, to some ; write . If , then also lost exactly one match, to some , in a later round than the one in which lost, by Lemma 1. The rounds are finite, so the chain reaches the only index that never lost, . Let . Then is in beaten, and by Lemma 1, . Take . Also for each , so is a largest item, .
Lemma 3 (the scan). Let be beaten. After line L12, is in and for each in .
Proof. The list is not empty, since and so won at least one match: the last round has two players. Line L11 sets to the first entry. Line L12 keeps the invariant " is the largest value among the entries of seen so far, and is one of them": an entry with replaces , and other entries are at most .
Conclusion. By Lemma 2, . Remove the index from ; the other items, sorted, are , so their largest is . By Lemmas 2 and 3, for each , where is the index of Lemma 2, and is one of these indices. So is the largest item other than , which is .
The count. The tournament makes comparisons. After rounds at most players are left, so there are at most rounds, and plays at most one match in each, so . Line L12 makes comparisons. The total is at most .