Proofs: Radix exchange sort
These are the human proofs of Radix exchange sort, at full length.
Radix exchange sort sorts non-negative integers full
This proof shows: correctness, termination.
Keys are integers in . For , write , the bits of above bit . A task is valid if all keys of have the same value of .
Fact 1. If and , then . If , then .
Proof. Write . Then and with , so . For , .
Lemma (partition). Let lines L5 to L9 run on a range with . They end, permute the range, and at the end every key of has bit equal to 0 and every key of has bit equal to 1.
Proof. At each test of line L6 the following holds: all keys of have bit 0, all keys of have bit 1, and . This is true at the start, with both parts empty. Line L7 moves only past keys with bit 0, and line L8 moves only past keys with bit 1, and both keep , because they stop when . If line L9 swaps, then , and by the stops of L7 and L8, has bit 1 and has bit 0; after the swap has bit 0 and has bit 1, so both parts grow by one and still holds. Each turn of the loop of line L6 either moves or in L7 or L8, or swaps and moves both, because if neither L7 nor L8 moves, then and the conditions of both scans fail, which means has bit 1 and has bit 0, so and line L9 runs. So decreases in each turn, and the loop ends with . Then the two parts cover the range.
Correctness. Call the state good if the tasks on have disjoint ranges and are valid, any two indices that are not in the same task have , and holds the input keys. The first task is valid, because for all keys, so the state is good at the start.
Pop a task . If , there is no pair inside it. If , all its keys are equal by Fact 1, so all pairs inside it are in order. In both cases dropping the task keeps the state good. Otherwise the lemma splits the range into a part with bit and a part with bit . Both parts agree on the bits above and on bit , so they are valid at . A key of the first part and a key of the second part are in order by Fact 1. Pairs with one index outside the range keep their relation, because the range holds the same keys. So the state stays good after line L10.
Termination. Each task pushed by line L10 has a bit index one lower than the popped task, and tasks with push nothing. So each task has , and the tasks form a binary tree of height at most . The tree is finite, so the loop ends.
Result. When is empty, every pair has , so is sorted, and it holds the input keys.