Algorithm Search⌘K

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 d0d_0 be the number of inversions of the input. Each change of AA is the exchange of line L6, so AA always holds a permutation of the input.

Invariant. At each test of line L2, 0≤i≤n0 \le i \le n, and A[0…i−1]A[0 \ldots i-1] is sorted.

Initialization. i=0i = 0, and the empty prefix is sorted.

A step forward (line L4). If i=0i = 0, the new prefix is A[0…0]A[0 \ldots 0], which is sorted. If i>0i > 0, the test found A[i−1]≤A[i]A[i-1] \le A[i]. The prefix A[0…i−1]A[0 \ldots i-1] is sorted and its last item is at most A[i]A[i], so A[0…i]A[0 \ldots i] is sorted. The step happens only when i<ni < n, so the new ii is at most nn.

A step back (lines L6 and L7). This needs i>0i > 0. The exchange changes only A[i−1]A[i-1] and A[i]A[i]. The new prefix is A[0…i−2]A[0 \ldots i-2], which was a part of the sorted prefix A[0…i−1]A[0 \ldots i-1] and is not changed by the exchange. So it is sorted, and the new ii is at least 0.

Correctness. The loop stops only when i≥ni \ge n, and with i≤ni \le n this means i=ni = n. By the invariant, A[0…n−1]A[0 \ldots n-1] is sorted.

Termination. A step back exchanges A[i−1]A[i-1] and A[i]A[i] with A[i−1]>A[i]A[i-1] > A[i]. 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 d0d_0 steps back. Between two steps back, and after the last one, the steps forward raise ii, which is at most nn, so there are at most nn of them in a row. So the loop makes finitely many steps.

The number of steps. When the loop stops, AA is sorted and has no inversions, so there were exactly d0d_0 steps back. Each step changes ii by +1+1 or −1-1, from 0 to nn, so there were n+d0n + d_0 steps forward, and n+2d0n + 2d_0 steps in total. ■\blacksquare

Back to Gnome sort