Kodewick
Start learning →
Counting sort and radix sort45 / 52

Counting sort and radix sort

Lesson 45 of 52 · Part 8 · Sorting · about 22 minutes

Counting sort counts how often each small integer appears and writes the values back in order, O(n + k) with no comparisons at all; radix sort deals numbers into 10 buckets by the ones digit, then the tens, then the hundreds, each pass stable.

The national exam scores of 10 million students need sorting, but there are only 751 possible scores, 0 to 750. Merge sort would make about 230 million comparisons. Think differently: count how many students got each score, then write the scores out from 0 to 750. That walks the 10 million scores once and the 751 counts once, with zero comparisons. That is counting sort. It and radix sort don't compare two values at all, so they get past the "about n log n at least" floor of comparison sorts, but only when the values are integers in a small range (or can be split into digits like that).

Counting sort: count how many of each value

The values are all between 0 and k. Make a list cnt of length k + 1, all zeros. Walk through a: for a value x, add one to cnt[x]. Then, for v from 0 to k, write v out as many times as it appeared.

a (left 6 boxes) and cnt[0..4] (right 5 boxes)acnt[0..4]3141300000001234567891011↑i

Counting 3 1 4 1 3 0: each value adds one to the box of cnt with that number; once counted, the values are written back from cnt, smallest first
main.py
1def counting_sort(a, k):2    cnt = [0] * (k + 1)          # cnt[v] = how many times v appears3    for x in a:4        cnt[x] += 15    out = []6    for v in range(k + 1):7        out.extend([v] * cnt[v])8    return out, cnt9 10print(counting_sort([3, 1, 4, 1, 3, 0], 4))11 12scores = [(i * 7919) % 101 for i in range(1000)]     # 1000 scores from 0 to 10013result, cnt = counting_sort(scores, 100)14print(result == sorted(scores), result[:8], cnt[:5])
Output
([0, 1, 1, 3, 3, 4], [1, 2, 0, 2, 1])
True [0, 0, 0, 0, 0, 0, 0, 0] [10, 10, 10, 10, 10]

Two loops in all: counting walks n items and writing back walks k + 1 counts, so it is O(n + k), with O(k) extra space for cnt. 1000 scores with 101 possible values take about 1100 steps; a comparison sort needs at least about 8500 comparisons.

Guess the outputA wrong guess is fine

The counting sort returns the sorted list and cnt. What does it print?

1def counting_sort(a, k):2    cnt = [0] * (k + 1)3    for x in a:4        cnt[x] += 15    out = []6    for v in range(k + 1):7        out.extend([v] * cnt[v])8    return out, cnt9 10print(counting_sort([2, 0, 2, 1], 2))
Choose one

The values are all 0 to 2. After counting 2 0 2 1 0 2, what are cnt[0] cnt[1] cnt[2]?

Exercise 1

Counting sort with negatives

Complete counting_sort(a): the integers in a may be negative. Find the smallest lo and largest hi first, count value x in cnt[x - lo], then write them back in order. An empty list returns an empty list.

It should print
[-1, -1, 0, 2, 3]
[5, 5, 5]
[-7, -5, -3]
[]
exercise1.py
1def counting_sort(a):2    if not a:3        return []4    lo, hi = min(a), max(a)5    cnt = [0] * (hi - lo + 1)6    # count: cnt[x - lo] += 1; write back: index i stands for the value i + lo7    return []8 9print(counting_sort([3, -1, 2, -1, 0]))10print(counting_sort([5, 5, 5]))11print(counting_sort([-3, -7, -5]))12print(counting_sort([]))
Output
Press Run or Ctrl+Enter

The stable version: prefix sums for places

The counting sort in the previous stage writes back the value itself, fine for bare integers. But you often sort records: students by score, moving the whole student, and keeping equal scores in their original order (stable). Then instead of [v] * cnt[v], first work out which box each key starts in:

  • Records with key v must come after every record with a smaller key. So v's starting place is pos[v] = cnt[0] + cnt[1] + … + cnt[v − 1], called a prefix sum.
  • Walk the records left to right; a record with key v goes into out[pos[v]], then pos[v] += 1, so the next record with the same key goes right after it. Placing left to right keeps earlier records earlier, so it is stable.
a (left 5 boxes) and out (right 5 boxes)aout3a1b2c1d3e0123456789↑i

The key is the number and the letter marks the original order. cnt[1..3] = 2, 1, 2, and the prefix sums give the starting places pos[1] = 0, pos[2] = 2, pos[3] = 3; left to right, each record goes into out[pos[key]], then pos[key] goes up by one
main.py
1def counting_sort_by(records, key, k):2    cnt = [0] * (k + 1)3    for r in records:4        cnt[key(r)] += 15    pos = [0] * (k + 1)                 # pos[v]: the box where key v starts6    for v in range(1, k + 1):7        pos[v] = pos[v - 1] + cnt[v - 1]8    out = [None] * len(records)9    for r in records:                   # placing left to right: stable10        v = key(r)11        out[pos[v]] = r12        pos[v] += 113    return out14 15records = [(3, "a"), (1, "b"), (2, "c"), (1, "d"), (3, "e")]16print(counting_sort_by(records, lambda r: r[0], 3))17 18students = [("Wang", 90), ("Li", 85), ("Zhang", 90), ("Zhao", 70), ("Chen", 85)]19print(counting_sort_by(students, lambda s: s[1], 100))
Output
[(1, 'b'), (1, 'd'), (2, 'c'), (3, 'a'), (3, 'e')]
[('Zhao', 70), ('Li', 85), ('Chen', 85), ('Wang', 90), ('Zhang', 90)]
Guess the outputA wrong guess is fine

Count first, then use prefix sums to work out where each key starts. What does it print?

1a = [3, 1, 3, 0, 3]2k = 33cnt = [0] * (k + 1)4for x in a:5    cnt[x] += 16pos = [0] * (k + 1)7for v in range(1, k + 1):8    pos[v] = pos[v - 1] + cnt[v - 1]9print(cnt, pos)
Fill inTap one to fill a blank; tap a blank to take it back

Which end the record-placing loop starts from decides whether it is stable. Fill in the blank so equal keys keep their original order.

1def counting_sort_by(records, key, k):2    cnt = [0] * (k + 1)3    for r in records:4        cnt[key(r)] += 15    pos = [0] * (k + 1)6    for v in range(1, k + 1):7        pos[v] = pos[v - 1] + cnt[v - 1]8    out = [None] * len(records)9    for r in :10        v = key(r)11        out[pos[v]] = r12        pos[v] += 113    return out14 15records = [(3, "a"), (1, "b"), (2, "c"), (1, "d"), (3, "e")]16print(counting_sort_by(records, lambda r: r[0], 3))

Radix sort: one digit at a time

When the values span a wide range, counting sort's cnt gets too long: values up to a billion need a billion boxes. Radix sort splits numbers into digits: first deal them by the ones digit into ten buckets, 0 to 9, and collect them in bucket order; then deal by the tens digit and collect; then by the hundreds… Each pass looks at one digit, and only 10 buckets are needed.

The key is that every pass is stable: when dealing by the tens digit, two numbers with the same tens digit keep the order the previous pass (by ones) gave them. So after the hundreds pass, numbers with the same hundreds digit are in tens order, and those with the same tens digit too are in ones order: everything is sorted. It starts from the lowest digit, so it is called LSD (least significant digit) radix sort.

ones0123456789

Pass 1 deals by the ones digit: 170 and 90 into bucket 0, 802 and 2 into bucket 2, 45 and 75 into bucket 5; then they are collected from bucket 0 to bucket 9
main.py
1def radix_sort(a):2    if not a:3        return a4    exp = 1                                  # 1: ones, 10: tens, 100: hundreds…5    while max(a) // exp > 0:6        buckets = [[] for _ in range(10)]    # 10 buckets, each a list7        for x in a:8            buckets[(x // exp) % 10].append(x)9        a = [x for b in buckets for x in b]  # collect in bucket order10        print(exp, a)11        exp *= 1012    return a13 14print(radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))
Output
1 [170, 90, 802, 2, 24, 45, 75, 66]
10 [802, 2, 24, 45, 66, 170, 75, 90]
100 [2, 24, 45, 66, 75, 90, 170, 802]
[2, 24, 45, 66, 75, 90, 170, 802]

Three-digit numbers take three passes. In pass 2, by tens, 802 and 2 both have tens digit 0, so they keep pass 1's order (802 before 2); in pass 3, by hundreds, 2's hundreds digit is 0, and only then does it move to the front.

Guess the outputA wrong guess is fine

Deal into buckets by the ones digit just once, then collect them in bucket order. What does it print?

1a = [21, 12, 31, 22]2buckets = [[] for _ in range(10)]3for x in a:4    buckets[x % 10].append(x)5print([x for b in buckets for x in b])
Choose one

A million 6-digit student numbers, sorted by radix sort with 10 values per digit: about how many steps?

Change it

These numbers have at most three digits. Change only the number in the green box so the program prints the fully sorted 329 355 436 457 657 720 839.

1a = [329, 457, 657, 839, 436, 720, 355]2exp = 13while exp <= :4    buckets = [[] for _ in range(10)]5    for x in a:6        buckets[(x // exp) % 10].append(x)7    a = [x for b in buckets for x in b]8    exp *= 109print(*a)
Should print
329 355 436 457 657 720 839
Exercise 2

Radix sort

Complete radix_sort(a): a holds non-negative integers. Starting from the ones digit, each pass uses 10 lists as buckets, deals by that digit and collects in bucket order, up to the highest digit. Return the sorted list and how many passes it made.

It should print
([2, 24, 45, 66, 75, 90, 170, 802], 3)
([1, 3, 5, 9], 1)
([1, 10, 100, 1000], 4)
([0, 0], 0)
exercise2.py
1def radix_sort(a):2    passes = 03    if not a:4        return a, passes5    exp = 16    # while max(a) // exp > 0: deal into buckets, collect, passes += 1, exp *= 107    return a, passes8 9print(radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))10print(radix_sort([5, 3, 9, 1]))11print(radix_sort([1000, 1, 10, 100]))12print(radix_sort([0, 0]))
Output
Press Run or Ctrl+Enter

When they beat comparison sorts

A sort that only compares two items at a time needs at least log₂(n!) comparisons, about n log₂ n − 1.44n. The reason: n items have n! orders, each comparison cuts the possibilities by at most half, and telling which of n! orders you have takes at least log₂(n!) comparisons. Counting and radix sort don't compare, so this limit doesn't apply:

main.py
1import math2 3def at_least(n):                  # log2(n!) ≈ n log2 n - 1.44 n4    return round(n * math.log2(n) - 1.4427 * n)5 6print(math.ceil(sum(math.log2(i) for i in range(1, 1001))), at_least(1000))   # exact and approximate7for n, k in [(1000, 100), (1000, 1000000), (10000000, 750)]:8    print("n =", n, "k =", k, " counting sort about", n + k, "steps", " comparison sort at least about", at_least(n), "comparisons")9 10digits = 311n = 100012print("radix sort, three digits:", digits, "passes × (n + 10) =", digits * (n + 10))
Output
8530 8523
n = 1000 k = 100  counting sort about 1100 steps  comparison sort at least about 8523 comparisons
n = 1000 k = 1000000  counting sort about 1001000 steps  comparison sort at least about 8523 comparisons
n = 10000000 k = 750  counting sort about 10000750 steps  comparison sort at least about 218107967 comparisons
radix sort, three digits: 3 passes × (n + 10) = 3030
  • The range k is about n or smaller (scores, ages, months, colour values 0–255): counting sort's O(n + k) wins by a lot.
  • k is far larger than n (1000 numbers, values up to a million): counting sort makes a million boxes and walks a million steps, far slower than a comparison sort.
  • Radix sort is O(d × (n + b)), where d is the number of digits and b the number of buckets (b = 10 for decimal). Integers with a fixed number of digits (phone numbers, 32-bit integers, equal-length strings) suit it well.
  • Decimals, or objects with a custom ordering: not possible; only comparison sorts work.
Counting sortRadix sort (LSD)Comparison sorts (merge, quick, sorted)
TimeO(n + k)O(d × (n + b))at least about n log n
Extra spaceO(k), plus O(n) for the stable versionO(n + b)O(1) to O(n)
Stablethe prefix-sum version isyes (each pass must be)merge sort and Timsort are
Needssmall integer keyskeys that split into digitsanything that can be compared

In interviews: "Is there a sort faster than O(n log n)?" Yes, but not a comparison sort. Comparison sorts have a floor of log₂(n!) ≈ n log n; counting sort is O(n + k) and radix sort O(d(n + b)), provided the keys are small-range integers or split into digits. Common problems: "sort a million people by age", "the numbers are between 0 and n, sort in O(n)", "sort colours" (only the values 0, 1, 2; LeetCode 75).

Choose one

Which data suits counting sort best?

Choose one

8 numbers have 8! = 40320 possible orders. Using only comparisons of two numbers, how many comparisons does it take at least, in the worst case, to tell which order it is?

How you write it at work

A counting sort written in Python is often no faster than sorted: sorted is written in C. Counting itself, though, you do every day: collections.Counter is a dict of "value → count" that counts anything, with no need to know the range in advance.

main.py
1from collections import Counter2 3grades = ["B", "A", "C", "B", "A", "B", "D"]4cnt = Counter(grades)5print(sorted(cnt.items()))6print(cnt.most_common(2))7print([g for g, c in sorted(cnt.items()) for _ in range(c)])8 9ages = [23, 35, 23, 41, 35, 23]10print(sorted(Counter(ages).items()))
Output
[('A', 2), ('B', 3), ('C', 1), ('D', 1)]
[('B', 3), ('A', 2)]
['A', 'A', 'B', 'B', 'B', 'C', 'D']
[(23, 3), (35, 2), (41, 1)]
  • For the count of each value: Counter, then sorted(cnt.items()) by value, or most_common(k) by count.
  • Just to sort: sorted.
  • Very few distinct values (say only 0, 1, 2) and lots of data: one pass to count, one to write back, O(n), and the answer interviewers want to see.
  • Radix sort is almost never hand-written in Python; it pays off in C or Go for sorting lots of integers or fixed-length keys.
Guess the outputA wrong guess is fine

Counter counts [2, 0, 2, 1, 0, 2]. What does it print?

1from collections import Counter2 3cnt = Counter([2, 0, 2, 1, 0, 2])4print(sorted(cnt.items()), cnt.most_common(1))

Summary

Take-away

Counting sort and radix sort

  • Counting: one pass of cnt[x] += 1, then write back from the smallest value, O(n + k), no comparisons
  • Stable version: prefix sums give each key's starting place, and records go into out left to right
  • Radix (LSD): deal into 10 buckets by ones, tens…, each pass stable, O(d × (n + 10))
  • Comparison sorts need at least log₂(n!) ≈ n log n; small-range integer keys make counting and radix faster
  • At work: Counter for counts, sorted for sorting
1cnt = [0] * (k + 1)2for x in a:3    cnt[x] += 14buckets = [[] for _ in range(10)]5buckets[(x // exp) % 10].append(x)