Counting sort
Six two-digit numbers sit in row A. First we sort them by their ones digit only: the key. Every key here is 0 to 3, so k = 4. Counting sort never compares two numbers. It uses each key as an array index.
Line 4 walks the list once and adds 1 to count[key] for each number. The keys 1, 2, 3, 0, 2, 1 give count = [1, 2, 2, 1]: one key 0, two 1s, two 2s and one 3.
Lines 5 and 6 add each counter to the one before it. Now count[d] says how many keys are d or less: [1, 2, 2, 1] becomes [1, 3, 5, 6]. So the numbers with key d end just before slot count[d].
Line 8 walks the list backwards. For each number, count[key] goes down by 1 and the number drops into that slot of row B. 21 lands in slot 2, 32 in slot 4, 10 in slot 0, and so on.
Row B is sorted by ones digit: 10, 31, 21, 12, 32, 23. Equal keys kept their input order: 31 still comes before 21, and 12 before 32. A sort that keeps ties in their input order is called stable.
Two loops touch each of the n numbers and one touches each of the k counters, so it takes Θ(n + k) time. It never compares two numbers, so the n log n bound for comparison sorts does not apply. But k must stay small.
Radix sort
Radix sort handles bigger keys one digit at a time, ones digit first. Row B is already sorted by ones. Now run the same counting sort on row B again, with the tens digit as the key, writing back into row A.
The tens digits of row B are 1, 3, 2, 1, 3, 2. Counting gives [0, 2, 2, 2]: no number has tens digit 0. Running totals turn that into [0, 2, 4, 6].
Walk row B backwards. Each number takes count[key] − 1 as its slot in row A: 23 lands in slot 3, 32 in slot 5, 12 in slot 1. Row A ends as 10, 12, 21, 23, 31, 32: sorted.
Why it works
31 and 32 share a tens digit, so they tied in pass 2. Stability kept them in their pass 1 order, which was by ones digit. So every tie is broken by the ones digit: that is numeric order. An unstable pass might swap them.
d digits means d passes of counting sort: Θ(d(n + k)) time. A 32-bit integer is four 8-bit digits, so 4 passes with 256 counters each, however big n is. With d fixed and k small, that is linear in n.
What happens
;; step 1/11 · keys row A 31 12 23 10 32 21 key 1 2 3 0 2 1 (ones digit) n = 6 numbers, k = 4 possible keys (0..3) key(x) = x % 10
Every digit in this example is 0, 1, 2 or 3, so k = 4 counters are enough. Ordinary decimal radix sort uses k = 10, one counter per digit, and the code below takes k as a parameter. The code follows COUNTING-SORT in CLRS §8.2: running totals, then placing from the back. Sedgewick and Wayne's key-indexed counting turns the counts into starting slots and places from the front instead. Both are stable and take time proportional to n + k.