Algorithm Search⌘K

Proofs: Proxmap sort

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

Proxmap sort sorts its input and is stable full

This proof shows: correctness, stability.

Let MM be non-decreasing with values in {0,…,m−1}\{0, \ldots, m - 1\}. Let H[k]H[k] be the hit counts of line L1, P[k]=H[0]+⋯+H[k−1]P[k] = H[0] + \cdots + H[k-1], and E[k]=P[k]+H[k]E[k] = P[k] + H[k]. The ranges Sk=[P[k],E[k])S_k = [P[k], E[k]) are disjoint, in the order of kk, and cover [0,n)[0, n), because E[k]=P[k+1]E[k] = P[k + 1] and E[m−1]=nE[m-1] = n.

Invariant. Before iteration ii of line L4, for each kk: 0≤F[k]≤H[k]0 \le F[k] \le H[k]; the cells B[P[k]…P[k]+F[k]−1]B[P[k] \ldots P[k] + F[k] - 1] hold the F[k]F[k] keys among A[0…i−1]A[0 \ldots i-1] with M(⋅)=kM(\cdot) = k, in non-decreasing order, with equal keys in input order; and the other cells of SkS_k are empty.

Initialization. F[k]=0F[k] = 0 and BB is empty, so the invariant holds for i=0i = 0.

Maintenance. Let x=A[i]x = A[i] and k=M(x)k = M(x). The keys of A[0…i−1]A[0 \ldots i - 1] with class kk number F[k]F[k], and xx is one more key of class kk, so F[k]+1≤H[k]F[k] + 1 \le H[k] and the cell j=P[k]+F[k]j = P[k] + F[k] of line L5 lies in SkS_k; it is empty by the invariant. Line L6 moves jj down while j>P[k]j > P[k] and B[j−1]>xB[j - 1] > x, and each move shifts B[j−1]B[j - 1] one cell right into the empty cell jj. This is one step of insertion sort on the sorted run B[P[k]…P[k]+F[k]−1]B[P[k] \ldots P[k] + F[k] - 1]: when the loop stops, every key in B[j+1…P[k]+F[k]]B[j + 1 \ldots P[k] + F[k]] is greater than xx, and j=P[k]j = P[k] or B[j−1]≤xB[j - 1] \le x. Line L7 puts xx at jj. The run is then sorted and has length F[k]+1F[k] + 1. Equal keys keep input order, since xx comes after all earlier keys in input order and it does not pass a key that is equal to it. No cell outside SkS_k is read or written, because j≥P[k]j \ge P[k] at all times. With F[k]F[k] increased in line L5, the invariant holds for i+1i + 1.

After the loop. With i=ni = n, each F[k]F[k] equals H[k]H[k], so each SkS_k is full and holds the keys of class kk in sorted, stable order. Take two cells p<qp < q. If they are in the same SkS_k, then B[p]≤B[q]B[p] \le B[q]. If p∈Skp \in S_k and q∈Sk′q \in S_{k'} with k<k′k < k', then M(B[p])=k<k′=M(B[q])M(B[p]) = k < k' = M(B[q]), and since MM is non-decreasing, B[p]>B[q]B[p] > B[q] is impossible, so B[p]≤B[q]B[p] \le B[q]. Two equal keys have the same class, so they are in the same SkS_k and in input order. Line L8 copies BB to AA. ■\blacksquare

Back to Proxmap sort