Algorithm Search⌘K

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 AA is an exchange of two items of AA (line L8), so AA always holds a permutation of the input. It remains to show that the loop of line L3 stops, and that AA is sorted when it stops.

Lemma 1. If i<ki < k and A[i]>A[k]A[i] > A[k], exchanging A[i]A[i] and A[k]A[k] lowers the number of inversions of AA by at least 1.

Proof. Let x=A[i]x = A[i] and y=A[k]y = A[k], with x>yx > y. The pair (i,k)(i, k) is an inversion before the exchange and not after it. Pairs that do not contain ii or kk do not change. Pairs with one index outside [i,k][i, k] keep the same set of two values on the same side, so their number of inversions does not change in total. For an index mm with i<m<ki < m < k and value z=A[m]z = A[m], the pairs (i,m)(i, m) and (m,k)(m, k) have [x>z]+[z>y][x > z] + [z > y] inversions before and [y>z]+[z>x][y > z] + [z > x] after. If z>xz > x the counts are 11 before and 11 after. If z<yz < y they are 11 and 11. If y≤z≤xy \le z \le x they are at least 11 before, as x>yx > y implies x>zx > z or z>yz > y, and 00 after. So no group of pairs gains inversions, and the pair (i,k)(i, k) loses one. □\square

Lemma 2. The values of gapgap at line L5 are non-increasing, and after at most ⌈log⁡13/10n⌉+1\lceil \log_{13/10} n \rceil + 1 passes, gap=1gap = 1 at each later pass.

Proof. Line L4 sets gapgap to max⁡(1,⌊10 gap/13⌋)\max(1, \lfloor 10\, gap / 13 \rfloor). If gap≥2gap \ge 2, then ⌊10 gap/13⌋≤10 gap/13<gap\lfloor 10\, gap/13 \rfloor \le 10\, gap / 13 < gap, so the value drops, and after kk passes it is at most n(10/13)kn (10/13)^k, which is less than 2 once k>log⁡13/10nk > \log_{13/10} n. If gap=1gap = 1, line L4 keeps it at 1. □\square

Termination. By Lemma 2, after finitely many passes each pass has gap=1gap = 1. Consider a pass with gap=1gap = 1. If it makes no exchange, line L5 set donedone 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 donedone true. Line L5 sets donedone to true only when gap=1gap = 1, and line L9 sets it to false at each exchange. So the last pass had gap=1gap = 1 and made no exchange: for each ii with 0≤i≤n−20 \le i \le n - 2, line L7 found A[i]≤A[i+1]A[i] \le A[i+1], and nothing changed AA after the test. So each pair of neighbours is in order, and since ≤\le is transitive, AA is in non-decreasing order. If n≤1n \le 1, the pass with gap=1gap = 1 has no step, and AA is sorted. ■\blacksquare

Back to Comb sort