Proofs: Cocktail shaker sort
These are the human proofs of Cocktail shaker sort, at full length.
Cocktail shaker sort sorts the array and stops full
This proof shows: correctness, termination.
Each change of is an exchange of two items of , so always holds a permutation of the input. It remains to show that the loop stops and that is then in non-decreasing order.
Invariant. At the test of line L2:
(I) and are sorted. Each item of is at most each item of , and each item of is at most each item of .
Initialization. and , so both outer parts are empty, and (I) holds.
Lemma 1 (the pass to the right). Assume (I) and before line L3. After line L7, is sorted, with the new , and each item of is at most each item of . The other parts of (I) still hold.
Proof. Let be the value of before the pass. The loop of line L4 has this invariant: before the step for , is a maximum of . It holds for . If , line L6 exchanges them, and then is the old , a maximum of . If not, is a maximum. So it holds for .
Let be the final value of . No exchange happened at a step , so for each with , the step found , and later steps did not touch . So is sorted. After the step for , is a maximum of , and the later steps do not change . So each item of is at most , which is at most each item of . The pass changes only , a permutation of its old items. By (I), these items are at most each item of , which is sorted. So is sorted, and each item of is at most each item of it: the items of by the argument above, and the items of by (I). Line L7 sets . The left part did not change, and its items are at most each item of , because that part holds the same items as before.
Lemma 2 (the pass to the left). After line L12, (I) holds with the new and .
Proof. This is the mirror image of Lemma 1. Let be the value of after line L7. The loop of line L9 has the invariant: before the step for , is a minimum of . Let be the final value of , so the last exchange was at , or if there was none. No exchange happened at a step , so is sorted, and after the step for , is a minimum of , which the later steps do not change. So is sorted, and each of its items is at most each item of . The pass changes only , so the right part of Lemma 1 still holds. If there was no exchange, , and the claim is that is sorted with each item at most : this holds because each step found . Line L12 sets .
By Lemmas 1 and 2, (I) holds at each test of line L2.
Termination. In a round with , the pass to the right sets to a value of in , so drops by at least 1. The pass to the left sets to a value in with the new , so does not drop. So drops by at least 1 in each round, and the loop stops after at most rounds.
Correctness at the end. Line L12 sets to a value of at most , so after a round . So when the loop stops, , or and there is nothing to sort. If , the array is , then , then . The two outer parts are sorted by (I). Each item of is at most each item to its right, and each item of is at most each item of . So is sorted.