Radix select returns the k-th smallest key and stops full
This proof shows: correctness, termination.
Let the keys be integers in [0,2w), let d=⌈w/r⌉, and write digj(x)=⌊x/2rj⌋mod2r for 0≤j<d. Each key is x=∑j=0d−1digj(x)2rj, because x<2w≤2rd. For a list S and 1≤k≤∣S∣, write sel(S,k) for the k-th entry of the sorted order of S. The claim is: for 1≤k≤n, RADIX-SELECT(A,k) stops and returns sel(A,k).
Termination. The loop of line L2 runs at most d passes, and each pass is a finite number of steps: line L5 reads ∣S∣ keys, and line L7 stops, as shown below, before b passes 2r−1.
Lemma (order by digits). Let x and y have the same digits digi for all i>j. If digj(x)<digj(y) then x<y.
Proof. The common higher digits contribute the same amount H to both. Then x≤H+digj(x)2rj+(2rj−1), since the lower digits add at most ∑i<j(2r−1)2ri=2rj−1, and y≥H+digj(y)2rj≥H+(digj(x)+1)2rj>x. □
Invariant. At the test of line L3 in the pass for digit j:
(R) 1≤k≤∣S∣; all keys of S have the same digits digi for each i>j; and sel(S,k)=sel(A,k0), where k0 is the rank given as input.
- Initialization. Before the first pass, j=d−1, S=A and k=k0. There are no digits above d−1, so (R) holds.
- Maintenance. Assume (R) at the pass for j, and ∣S∣>1. After line L5, C[c] is the number of keys of S with digit j equal to c, and ∑cC[c]=∣S∣≥k. Line L7 keeps k≥1 and stops at the least b with k≤C[b]; such a b exists because the sums C[0]+⋯+C[c] reach ∣S∣. Write k′ for the value of k after line L7 and c0=C[0]+⋯+C[b−1]; then k′=k−c0 and 1≤k′≤C[b]. Let B be the list of line L8. By (R) and the lemma, each key of S with digit j less than b is less than each key of B, and each key with digit j greater than b is greater. So the sorted order of S is the c0 keys of the lower buckets, then the sorted B, then the rest, and sel(S,k)=sel(B,k−c0)=sel(B,k′). All keys of B agree on the digits above j and on digit j. So (R) holds for the next pass, with j−1, S=B and k=k′.
Conclusion. If line L3 returns, then ∣S∣=1, so k=1 by (R), and S[1]=sel(S,1)=sel(A,k0). Otherwise the loop ends after the pass for j=0; by the maintenance step, the keys of S then agree on all digits dig0,…,digd−1, so they are all equal, and 1≤k≤∣S∣. Hence S[1]=sel(S,k)=sel(A,k0), which line L9 returns. ■