Proofs: Comb sort
These are the human proofs of Comb sort, at full length.
Comb sort sorts the array and stops full
This proof shows: correctness, termination.
Each change of is an exchange of two items of (line L8), so always holds a permutation of the input. It remains to show that the loop of line L3 stops, and that is sorted when it stops.
Lemma 1. If and , exchanging and lowers the number of inversions of by at least 1.
Proof. Let and , with . The pair is an inversion before the exchange and not after it. Pairs that do not contain or do not change. Pairs with one index outside keep the same set of two values on the same side, so their number of inversions does not change in total. For an index with and value , the pairs and have inversions before and after. If the counts are before and after. If they are and . If they are at least before, as implies or , and after. So no group of pairs gains inversions, and the pair loses one.
Lemma 2. The values of at line L5 are non-increasing, and after at most passes, at each later pass.
Proof. Line L4 sets to . If , then , so the value drops, and after passes it is at most , which is less than 2 once . If , line L4 keeps it at 1.
Termination. By Lemma 2, after finitely many passes each pass has . Consider a pass with . If it makes no exchange, line L5 set to true and line L9 never ran, so the loop stops at the next test of line L3. If it makes an exchange, the number of inversions drops by at least 1, by Lemma 1, and no exchange raises it. The number of inversions is a non-negative integer, so only finitely many passes make an exchange. So the loop stops.
Correctness at the end. The loop stops only at a test of line L3 that finds true. Line L5 sets to true only when , and line L9 sets it to false at each exchange. So the last pass had and made no exchange: for each with , line L7 found , and nothing changed after the test. So each pair of neighbours is in order, and since is transitive, is in non-decreasing order. If , the pass with has no step, and is sorted.