Proofs: Counting sort
These are the human proofs of Counting sort, at full length.
Counting sort sorts the items and keeps equal keys in input order full
This proof shows: correctness, stability.
Write for , and assume that for each . For a key value let and let , the number of items with a key less than . Block is the index range of . The blocks for are disjoint, they follow each other in order of , and together they cover , because and .
Step 1 (pass 1). At the test of line L2 with index , for each . This holds for by line L1. Line L3 adds 1 to exactly the entry , so it holds for . When the loop stops, and .
Step 2 (pass 2). At the test of line L5 with index , we claim that , that for , and that for . For this holds by line L4 and Step 1, since . Line L6 saves , sets , and sets . So the claim holds for . At the end, for each .
Step 3 (pass 3). Let be the indices with , in increasing order. The invariant at the test of line L8 with index is:
(P) For each , , and for .
For each is empty and by Step 2, so (P) holds. Assume (P) at index , and let . Then is followed by . Line L9 writes at index . This index is in block , because : the item itself has key and is not in . So the write does not touch the slots of another block, and it does not touch the earlier slots of block . Line L10 adds 1 to . The lists and counters of all other keys do not change. So (P) holds at index .
Step 4 (the result). When the loop stops, , and (P) says that block holds the items with key , in increasing order of their input index, for each . The blocks cover and are in order of . So each slot of is written exactly once, holds each item of exactly once, the keys in are non-decreasing, and items with equal keys appear in their input order.
Termination. Each of the three loops has a fixed range of or steps, and each step does a fixed number of operations.