TExcelTAD

Radix Sort

Counting sort is fast for small values but useless for large ones such as 6-digit postcodes. Radix sort fixes this by sorting one digit at a time. It starts with the least significant digit (the ones), then the tens, then the hundreds. Each pass uses a stable sort on that single digit, so only ten possible keys (0–9) ever appear.

This version is called LSD radix sort (least significant digit first).

How it works

  1. Put every number into one of 10 buckets according to its ones digit, keeping the input order inside each bucket.
  2. Read the buckets back from bucket 0 to bucket 9. The array is now sorted by the last digit.
  3. Repeat with the tens digit, then the hundreds, and so on, up to the number of digits of the largest value.

Why does it work? After sorting by the tens digit, numbers with equal tens digits are still ordered by their ones digit, because the pass was stable. After the final pass, the numbers are ordered by the leading digit, ties are broken by the next digit, and so on: exactly numeric order.

Implementation with buckets

python · try it yourself
def radix_sort(arr):
    exp = 1                                   # 1, 10, 100, ...
    biggest = max(arr)
    while biggest // exp > 0:
        buckets = [[] for _ in range(10)]
        for v in arr:
            buckets[(v // exp) % 10].append(v)
        arr = [v for bucket in buckets for v in bucket]
        print(f"by digit {exp:>3}: {arr}")
        exp *= 10
    return arr

print(radix_sort([512, 83, 340, 7, 291, 66, 405, 118]))
by digit   1: [340, 291, 512, 83, 405, 66, 7, 118]
by digit  10: [405, 7, 512, 118, 340, 66, 83, 291]
by digit 100: [7, 66, 83, 118, 291, 340, 405, 512]
[7, 66, 83, 118, 291, 340, 405, 512]

Follow 83 and 66: after the ones pass 83 comes first (3 < 6), after the tens pass 66 comes first (6 < 8). The largest number has three digits, so three passes are enough.

Looking inside one pass

Here are the buckets of the first pass. The digit of each number decides its bucket, and the order inside a bucket is the input order:

python · try it yourself
values = [512, 83, 340, 7, 291, 66, 405, 118]
buckets = {d: [] for d in range(10)}
for v in values:
    buckets[v % 10].append(v)
for d, items in buckets.items():
    if items:
        print(f"bucket {d}: {items}")
bucket 0: [340]
bucket 1: [291]
bucket 2: [512]
bucket 3: [83]
bucket 5: [405]
bucket 6: [66]
bucket 7: [7]
bucket 8: [118]

Using counting sort for each digit

Instead of lists of buckets, each pass can be the stable counting sort from the previous lesson, with the digit as the key. This uses flat arrays only, which is how radix sort is usually implemented in lower-level languages:

python · try it yourself
def counting_pass(arr, exp):
    counts = [0] * 10
    for v in arr:
        counts[(v // exp) % 10] += 1
    for d in range(1, 10):                    # running total: end position + 1
        counts[d] += counts[d - 1]
    output = [0] * len(arr)
    for v in reversed(arr):                   # right to left keeps it stable
        d = (v // exp) % 10
        counts[d] -= 1
        output[counts[d]] = v
    return output

def radix_sort_counting(arr):
    exp = 1
    while max(arr) // exp > 0:
        arr = counting_pass(arr, exp)
        exp *= 10
    return arr

print(radix_sort_counting([512, 83, 340, 7, 291, 66, 405, 118]))
print(radix_sort_counting([90210, 10115, 75001, 30301, 10001]))
[7, 66, 83, 118, 291, 340, 405, 512]
[10001, 10115, 30301, 75001, 90210]

Filling from the right end with decreasing positions is the mirror image of the left-to-right version with starting positions; both keep the pass stable.

Sorting strings of equal length

Radix sort is not limited to numbers. Any key that splits into "digits" works, for example fixed-length codes, sorted character by character from the last position:

python · try it yourself
def radix_sort_strings(words):
    width = len(words[0])
    for pos in range(width - 1, -1, -1):
        words = sorted(words, key=lambda w: w[pos])    # sorted() is stable
        print(f"by position {pos}: {words}")
    return words

radix_sort_strings(["dab", "cab", "fad", "bad", "dad", "ebb", "ace"])
by position 2: ['dab', 'cab', 'ebb', 'fad', 'bad', 'dad', 'ace']
by position 1: ['dab', 'cab', 'fad', 'bad', 'dad', 'ebb', 'ace']
by position 0: ['ace', 'bad', 'cab', 'dab', 'dad', 'ebb', 'fad']

Properties

Property LSD radix sort
Time O(d · (n + b)) for d digits in base b (here b = 10)
Extra memory O(n + b)
Stable? Yes
Requirements integer keys (or fixed-length strings); negatives need special handling

When the number of digits d is small and fixed, this is effectively O(n), faster than any comparison sort.

Tip: A larger base means fewer passes. Real implementations often use base 256 and sort one byte at a time, so a 32-bit integer needs only 4 passes.

Test yourself

In LSD radix sort, which digit is used in the first pass?

  1. The most significant digit
  2. The least significant (ones) digit
  3. The middle digit
  4. Any digit

Why must each digit pass be stable?

  1. To use less memory
  2. So the order from earlier (less significant) passes is kept for equal digits
  3. Because unstable sorts are slower
  4. It doesn't need to be

How many passes does base-10 radix sort need if the largest value is 40,500?

  1. 2
  2. 4
  3. 5
  4. 40,500