Proofs: Median of medians
These are the human proofs of Median of medians, at full length.
Median of medians returns the k-th smallest item and stops full
This proof shows: correctness, termination.
For a list of items and , write for the -th entry of a sorted order of . All sorted orders of have the same entries, so this value is well defined.
Claim. For each list of items and each with , SELECT stops and returns .
Lemma (split). Let be an item, and let , and be the items of that are less than, equal to and greater than . Then
Proof. The order is total, so each item of is in exactly one of the three lists. Sort and , and write as copies of . The list "sorted , then , then sorted " is sorted: each item of is less than , and each item of is greater than . It holds the items of , so it is a sorted order of . Its entries to are the sorted , its entries to are equal to , and its entry is the entry of the sorted .
Proof of the claim. By strong induction on . The hypothesis says that SELECT stops and returns for each list of items and each .
-
Base, . Line L1 sorts by insertion sort, which stops and is correct, and returns its entry of rank , which is by definition.
-
Step, . Assume for each .
- Line L2 makes groups. Each group is not empty, and because .
- Line L3 makes the list of group medians. Each is an item of .
- Line L4 calls SELECT. Here and , so by the call stops and returns , which is an item of and so of .
- Line L5 makes , and as in the lemma. Since is an item of , , so and .
- If , line L6 calls SELECT with . By it returns , which is by the lemma.
- If , line L7 returns , which is by the lemma.
- Otherwise , so satisfies . Line L8 calls SELECT, which by returns , which is by the lemma.
In each case the call stops, because each recursive call stops, and returns .
So holds for each . The proof uses no property of except that it is an item of . The choice of as the median of the medians matters only for the running time, which the Complexity section of the page proves.