Proofs: Pancake sort
These are the human proofs of Pancake sort, at full length.
Pancake sort sorts the array with prefix reversals full
This proof shows: correctness.
FLIP reverses . It permutes the items of and changes no other index. So each step of the algorithm keeps the multiset of the items of the array.
Invariant. Before the step of line L1 for , with , and also when the loop ends with :
(S) is sorted, and each item of is at most each item of .
Start. For the part is empty, so (S) holds.
Step. Assume (S) before the step for . Line L2 sets to the index of a largest item of , so .
- If , nothing changes, and .
- If , line L4 is skipped, and line L5 reverses , which moves to index .
- If , line L4 reverses , which moves to index 0 and keeps the items of , since . Then line L5 moves to index .
In each case, the flips are of prefixes that end at an index less than , so does not change, and holds the same items as before, with . Since is a largest item of this prefix, each item of is at most . By (S), is at most each item of , so is sorted. Each item of was in , so it is at most each item of , and at most . So (S) holds for .
Theorem. PANCAKE-SORT stops, changes only by prefix reversals, and leaves sorted, with the same items.
Proof. The loop runs for , and each step does a scan of items and at most two flips, so the algorithm stops. All changes are flips, so the items are kept. If , the loop does not run, and the array is sorted. Otherwise, at the end (S) holds for : is sorted, and is at most each of its items. So is sorted.
The number of flips. Each step makes at most 2 flips, and the step for makes at most one, because then : for there is no flip, and for only line L5 runs. So for there are at most flips.