Proofs: Introselect
These are the human proofs of Introselect, at full length.
Introselect returns the k-th smallest item and stops full
This proof shows: correctness, termination.
Let be the multiset of the input items and its sorted order. The claim is: for , INTROSELECT stops and returns . We use two facts proved on their own pages: MOM-SELECT stops and returns the item of rank of a list (median of medians), and PARTITION3 permutes , changes no other entry, and returns with , each item of less than , each item of equal to , and each item of greater than (the three-way template of partition around a pivot).
Invariant. At each test of line L2:
(I) is a permutation of ; ; each item of is at most each item of ; and each item of is at most each item of .
Consequence. Under (I), a sorted order of is: a sorted order of , then the sorted block of , then a sorted order of . So , the item of rank of the block.
- Initialization. Line L1 sets to a copy of , , and , so and the outer parts are empty.
- Maintenance. Assume (I) and , and that lines L3 and L6 do not return. Line L4 picks among three items of the block, so is an item of the block. Line L5 gives as above, and since is in the block, . Line L6 did not return, so or . If , line L8 sets : then , and the items now to the right of the block are of the old block, which are at least and so at least each item of , together with the old right part, which (I) bounds below by each item of the old block. If , line L8 sets , and the argument is the mirror one. Line L9 changes only the counter. So (I) holds again.
- Termination. Each pass that does not return replaces by or , which leaves out the copies of . So drops by at least , and the loop runs at most passes.
Conclusion. The run ends in one of three ways.
- Line L3 returns MOM-SELECT. By (I), , so the rank is valid, and the call stops and returns , which is by the consequence of (I).
- Line L6 returns with . After line L5 the block is , then copies of , then , so the sorted block has for . The partition kept (I) true, since it only permuted the block, so by the consequence of (I), .
- The loop stops with and line L10 returns . By (I), , so and ; by the consequence of (I), .
In each case the result is .