ENع
←Counting and radix sort
Lesson 32 · Greedy and divide and conquer

Counting sort and radix sort

14 min11 steps5 questionsAdvanced
About this lesson

"Why comparison sorts can't beat n log n" proves a floor for sorts that only compare. Counting sort steps around it: it never compares two items, it uses each item's small whole-number key as a list index. Watch six numbers get counted, totalled and dropped into place by their ones digit, then sorted fully by radix sort, one stable pass per digit. It builds on the Software lessons on sorting (insertion sort, merge sort, Timsort).

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 32 · Interactive
01 / 11

Sort by a small key

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.

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
Loading figure…
or ← →
Read the lesson step by step
  1. Sort by a small key

    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.

    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
  2. Count each key

    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.

    for x in a: count[key(x)] += 1
      31  key 1   count = [0, 1, 0, 0]
      12  key 2   count = [0, 1, 1, 0]
      23  key 3   count = [0, 1, 1, 1]
      10  key 0   count = [1, 1, 1, 1]
      32  key 2   count = [1, 1, 2, 1]
      21  key 1   count = [1, 2, 2, 1]
  3. Running totals

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

    for d in range(1, k): count[d] += count[d - 1]
      start          count = [1, 2, 2, 1]
      d = 1          count = [1, 3, 2, 1]
      d = 2          count = [1, 3, 5, 1]
      d = 3          count = [1, 3, 5, 6]
    
    keys ≤ 0: 1, ≤ 1: 3, ≤ 2: 5, ≤ 3: 6
  4. Place from the back

    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.

    for x in reversed(a): count[key(x)] -= 1; out[count[key(x)]] = x
      21  key 1  → slot 2   count = [1, 2, 5, 6]
      32  key 2  → slot 4   count = [1, 2, 4, 6]
      10  key 0  → slot 0   count = [0, 2, 4, 6]
      23  key 3  → slot 5   count = [0, 2, 4, 5]
      12  key 2  → slot 3   count = [0, 2, 3, 5]
      31  key 1  → slot 1   count = [0, 1, 3, 5]
    
    row B     10  31  21  12  32  23
  5. Ties keep their order

    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.

    row A     31  12  23  10  32  21
    row B     10  31  21  12  32  23
    
    key 1: 31 then 21   (same order as row A)
    key 2: 12 then 32   (same order as row A)
    placing from the back fills each key's slots from the right, so ties never swap
  6. Θ(n + k), no comparisons

    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.

    line 3   for x in a            n times
    line 5   for d in range(1, k)  k - 1 times
    line 8   for x in reversed(a)  n times
    
    time   Θ(n + k)
    extra memory: count (k cells) + out (n cells)
    here: n = 6, k = 4
    keys up to 2**32 would need about 4.3 billion counters
  7. Next digit: the tens

    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.

    row B     10  31  21  12  32  23
    key        1   3   2   1   3   2   (tens digit)
    
    key(x) = x // 10 % 10
    pass 1 sorted by ones, pass 2 sorts by tens
  8. Count and total the tens

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

    count the keys
      10  key 1   count = [0, 1, 0, 0]
      31  key 3   count = [0, 1, 0, 1]
      21  key 2   count = [0, 1, 1, 1]
      12  key 1   count = [0, 2, 1, 1]
      32  key 3   count = [0, 2, 1, 2]
      23  key 2   count = [0, 2, 2, 2]
    running totals
      d = 1          count = [0, 2, 2, 2]
      d = 2          count = [0, 2, 4, 2]
      d = 3          count = [0, 2, 4, 6]
  9. Place from the back again

    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.

      23  key 2  → slot 3   count = [0, 2, 3, 6]
      32  key 3  → slot 5   count = [0, 2, 3, 5]
      12  key 1  → slot 1   count = [0, 1, 3, 5]
      21  key 2  → slot 2   count = [0, 1, 2, 5]
      31  key 3  → slot 4   count = [0, 1, 2, 4]
      10  key 1  → slot 0   count = [0, 0, 2, 4]
    
    row A     10  12  21  23  31  32
  10. Why the order holds

    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.

    after 1   10  31  21  12  32  23
    after 2   10  12  21  23  31  32
    
    tens 1: 10 then 12   (order from pass 1)
    tens 2: 21 then 23
    tens 3: 31 then 32
    ones digit first, most significant digit last
  11. Radix sort's cost

    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.

    time   Θ(d · (n + k))
    here: d = 2 passes, n = 6, k = 4
    
    32-bit keys as 8-bit digits: d = 4, k = 256
      4 · (n + 256) steps of counting work
    
    def radix_sort(a, d, k=10):
        for p in range(d):
            a = counting_sort(a, lambda x: x // k**p % k, k)
        return a

Quiz Unlocks after the last step.