Algorithm Search⌘K

Proofs: Pigeonhole sort

These are the human proofs of Pigeonhole sort, at full length.

Pigeonhole sort sorts the items and is stable full

This proof shows: correctness, stability, termination.

Let n≥1n \ge 1 (for n=0n = 0 line L1 returns, and the empty array is sorted). Let κi=key(A[i])\kappa_i = \mathrm{key}(A[i]) for the input array, lo=min⁡iκilo = \min_i \kappa_i, hi=max⁡iκihi = \max_i \kappa_i and k=hi−lo+1≥1k = hi - lo + 1 \ge 1.

Step 1 (the holes exist). For each ii, lo≤κi≤hilo \le \kappa_i \le hi, so 0≤κi−lo≤k−10 \le \kappa_i - lo \le k - 1. So line L6 appends to one of the kk holes made by line L4.

Step 2 (the scatter). At the test of line L5 with index ii, for each hh, the hole H[h]H[h] holds the items A[j]A[j] with j<ij < i and κj=lo+h\kappa_j = lo + h, in increasing order of jj. For i=0i = 0 all holes are empty. Step ii appends A[i]A[i] at the end of H[κi−lo]H[\kappa_i - lo] and changes no other hole, so the claim holds for i+1i + 1. At i=ni = n, hole hh holds all items with key lo+hlo + h, in input order. The array AA is not written in this loop, so it still holds the input.

Step 3 (the gather). At the start of the step of line L8 with index hh, j=∣H[0]∣+⋯+∣H[h−1]∣j = |H[0]| + \cdots + |H[h-1]|, and A[0…j−1]A[0 \ldots j-1] holds the items of H[0],…,H[h−1]H[0], \ldots, H[h-1], each hole in its order, one hole after the other. For h=0h = 0, j=0j = 0 by line L7. The loop of lines L9 and L10 writes the ∣H[h]∣|H[h]| items of H[h]H[h] to A[j],A[j+1],…A[j], A[j+1], \ldots in order and adds ∣H[h]∣|H[h]| to jj, so the claim holds for h+1h + 1. The writes do not lose data, because all items are in the holes after Step 2.

Step 4 (the result). At the end, h=kh = k and j=∑h∣H[h]∣=nj = \sum_h |H[h]| = n. So AA holds each input item exactly once. Its keys are non-decreasing, because the holes are written in increasing order of hh and hole hh holds only the key lo+hlo + h. Two items with the same key are in the same hole, in input order by Step 2, and they are written in that order. So the sort is stable. ■\blacksquare

Termination. Each loop has a fixed number of steps: nn for line L5, kk for line L8, and ∣H[h]∣|H[h]| for line L9, with ∑h∣H[h]∣=n\sum_h |H[h]| = n.

Back to Pigeonhole sort