Proofs: Gnome sort
These are the human proofs of Gnome sort, at full length.
Gnome sort sorts the array and stops after n + 2d steps full
This proof shows: correctness, termination.
Let be the number of inversions of the input. Each change of is the exchange of line L6, so always holds a permutation of the input.
Invariant. At each test of line L2, , and is sorted.
Initialization. , and the empty prefix is sorted.
A step forward (line L4). If , the new prefix is , which is sorted. If , the test found . The prefix is sorted and its last item is at most , so is sorted. The step happens only when , so the new is at most .
A step back (lines L6 and L7). This needs . The exchange changes only and . The new prefix is , which was a part of the sorted prefix and is not changed by the exchange. So it is sorted, and the new is at least 0.
Correctness. The loop stops only when , and with this means . By the invariant, is sorted.
Termination. A step back exchanges and with . This pair is an inversion before the exchange and not after it, and no other pair changes its order, because the two items are neighbours. So each step back lowers the number of inversions by exactly 1, and a step forward does not change it. The number of inversions is never negative, so there are at most steps back. Between two steps back, and after the last one, the steps forward raise , which is at most , so there are at most of them in a row. So the loop makes finitely many steps.
The number of steps. When the loop stops, is sorted and has no inversions, so there were exactly steps back. Each step changes by or , from 0 to , so there were steps forward, and steps in total.