1def counting_sort(a, key, k):2 count = [0] * k3 for x in a:4 count[key(x)] += 15 for d in range(1, k):6 count[d] += count[d - 1]7 out = [None] * len(a)8 for x in reversed(a):9 count[key(x)] -= 110 out[count[key(x)]] = x11 return out012345count[0]count[1]count[2]count[3]012345311223103221
Number blocks: the list; the red digit is the key of this passCounters count[0..3]: one per possible keyA hopping token: one count or running-total updateCounting sort on the ones digit: count each key, turn the counts into running totals, then place every number from the back of row A into the row B slot its counter names. Radix sort runs the same stable pass again on the tens digit, from row B back into row A, which ends sorted.

Counting sort

  1. 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.

Radix sort

Why it works

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.