Skip to content
BytePatterns

Radix Sort

Sorting: lesson 10 of 10

Sort by the last digit first, and never compare a thing.

Lesson 10 of 10 · 5 min

Radix Sort

Step 1 of 7

Radix sort never compares two numbers. It sorts by one digit at a time, starting from the right.

The Idea

Radix sort is counting sort run once per digit, starting from the least significant one. Each pass drops every number into one of ten buckets and collects them back in bucket order. Because a pass is stable, numbers that tie on the current digit keep the order the previous pass gave them — which is exactly why starting from the right works. Cost is d passes over n numbers, with no comparisons at all.

Real-World Example

Old postal sorting. Letters are thrown into pigeonholes by the last digit of the code, gathered up in order, and thrown again by the next digit. After the final round the stack is in delivery order and nobody read a full address.

The Code

def radix_sort(nums):
    place = 1
    while place <= max(nums):
        buckets = [[] for _ in range(10)]
        for x in nums:
            buckets[(x // place) % 10].append(x)   # ties keep their order
        nums = [x for b in buckets for x in b]     # collect 0..9 in order
        place *= 10
    return nums

print(radix_sort([170, 45, 75, 90, 2, 802]))   # [2, 45, 75, 90, 170, 802]

Python

Your turn

What does this print?

nums = [53, 12, 21, 45]
buckets = [[] for _ in range(10)]
for x in nums:
  buckets[x % 10].append(x)
print([x for b in buckets for x in b])

Mini quiz

1 / 3

Why must every pass be stable?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.