Proofs: Floyd-Rivest selection
These are the human proofs of Floyd-Rivest selection, at full length.
Floyd-Rivest selection 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 have the same entries, so it is well defined.
Claim. For each list with items, each with , and each outcome of the random draws, FR-SELECT stops and returns .
Lemma (split by two pivots). Let be items, and let , and be the items of that are less than , in , and greater than . Then
Proof. The order is total, so each item is in exactly one part. Each item of is less than , which is at most each item of , and each item of is at most , which is less than each item of . So the list "sorted , sorted , sorted " is a sorted order of , and its entry is the entry named in the case.
Lines L7 and L8 build these parts. In line L7, an item goes to if ; otherwise , and it goes to if , and to if . Line L8 tests first and second; since , an item with is not greater than , so again each item goes to the part the lemma names.
Proof of the claim. By strong induction on . Assume the claim for all lists with fewer than items.
- Line L1. If , sorting returns by definition.
- Lines L2 to L5. Now , so satisfies , and is a list of items of . Line L4 gives : the lower end is at least by the max, the upper end is at most by the min, and with since , and since . By the hypothesis for , line L5 returns and , and because . Both are items of .
- Lines L9 and L10. is in and is not less than itself, so and ; likewise and . If , the call of line L9 has , and by the hypothesis and the lemma it returns . If , then , and the same argument applies to line L10.
- Lines L11 and L12. Otherwise , so . If , line L11 returns by sorting. If , line L12 calls FR-SELECT on a shorter list, which by the hypothesis returns , which is by the lemma.
Each case either returns directly or makes recursive calls on lists with fewer than items, each of which stops by the hypothesis, so the call stops and returns . The proof uses no property of the sample except that is a list of items of , so it holds for every outcome of the draws.