Proofs: Bogosort
These are the human proofs of Bogosort, at full length.
Bogosort is correct when it stops, and it stops with probability 1 full
This proof shows: correctness, termination.
Lemma 1 (IS-SORTED). IS-SORTED returns true if and only if for each with , which is the case exactly when is in non-decreasing order.
Proof. The loop of line L3 tests the pairs for in order. If some pair has , line L4 returns false at the first such pair. If no pair has it, the loop ends and line L5 returns true. A sequence is non-decreasing exactly when each pair of neighbours is in order, because is transitive.
Lemma 2 (SHUFFLE). After SHUFFLE, holds the same multiset of items, and if the random integers of line L7 are uniform and independent, each of the arrangements of the positions has probability .
Proof. Each step of line L8 is an exchange, so the multiset does not change. For the distribution, the loop makes choices, the choice for among values, so there are equally likely sequences of choices. Each sequence gives a different arrangement: the choice for fixes which item ends at position , which is never touched again, and by induction the later choices fix the remaining positions. So the sequences give the arrangements, one each. This is the proof of CLRS, Section 5.3.
Theorem. (a) If BOGOSORT returns, holds the input items in non-decreasing order. (b) BOGOSORT returns with probability 1, and on distinct keys that are not sorted, the number of shuffles satisfies and .
Proof. (a) The loop of line L1 exits only when IS-SORTED returns true, so by Lemma 1 the array is in non-decreasing order at that time. By Lemma 2 and because IS-SORTED does not change , it holds the input multiset.
(b) Let the input have the key values with multiplicities . Of the arrangements of the positions, exactly give a non-decreasing array, so by Lemma 2 each shuffle gives a sorted array with probability . The shuffles use fresh random integers, so the events "shuffle gives a sorted array" are independent, each with probability . If the input is not sorted, the run makes more than shuffles exactly when the first shuffles all give unsorted arrays, so . This tends to 0 as grows, so , and the run stops with probability 1. Then
For distinct keys, and . If the input is sorted, .