Sub topic 9
LSD Radix Sort: Least Significant Digit First
Counting sort is fast only when the key range k is small. A 32-bit integer can take about four billion values, so one counting sort over the full key would need a count array with four billion entries. LSD radix sort avoids that. It sorts on one small digit at a time, starting with the least significant digit (LSD), and runs a stable counting sort for each digit. Every pass uses a small count array, and after the last pass the whole array is sorted.
This chapter assumes you already know three things from earlier chapters. You know the stable counting sort by key built from prefix sums. You know what stability means. You know how a key splits into digits of a chosen radix. This chapter builds the algorithm, traces it by hand, and covers the mistakes people make when implementing it. The next chapter proves why it works, and the one after that analyzes its cost.
The algorithm in one paragraph
Pick a radix b, the number of possible values for one digit. Let d be the number of digits needed for the largest key. Then run d passes. Pass i sorts the whole array by digit i alone, using a stable counting sort with b buckets. Pass 0 uses the ones digit, pass 1 the next digit up, and so on. The output of each pass is the input to the next. Nothing else happens. The algorithm never compares two elements, and no pass looks at more than one digit.
A hand trace in base 10
Base 10 is the easiest radix for people to follow, so start there. The input is:
[170, 45, 75, 90, 802, 24, 2, 66]
The largest key is 802, which has three decimal digits, so the sort needs three passes. Short numbers act as if they have leading zeros: 2 is treated as 002.
| Pass | Digit used | Digit of each element (in input order) | Output of the pass |
|---|---|---|---|
| 0 | ones | 0, 5, 5, 0, 2, 4, 2, 6 | 170, 90, 802, 2, 24, 45, 75, 66 |
| 1 | tens | 7, 9, 0, 0, 2, 4, 7, 6 | 802, 2, 24, 45, 66, 170, 75, 90 |
| 2 | hundreds | 8, 0, 0, 0, 0, 1, 0, 0 | 2, 24, 45, 66, 75, 90, 170, 802 |
In each row, "digit of each element" refers to the input of that pass, which is the output of the row above. Look at pass 1. Both 802 and 2 have tens digit 0. They come out as 802 then 2 because that was their order after pass 0. That order is wrong for the final result, and pass 2 fixes it: 2 has hundreds digit 0 and 802 has hundreds digit 8. Now look at 170 and 75 in pass 2. Both have hundreds digit 0 or 1, and the 0-digit group (2, 24, 45, 66, 75, 90) keeps the order pass 1 gave it. Because the pass is stable, it keeps that correct order instead of scrambling it.
That is the pattern to remember. A later pass decides the order between elements whose current digits differ. When the current digits tie, the pass falls back on the order left by earlier passes.
Implementation in base 10
Here is a direct translation of the trace. It uses the stable counting sort from the earlier chapter, repeated here so the block runs on its own.
def counting_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..k."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
# Exclusive prefix sums: counts[v] becomes the first output index for key v.
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items: # forward pass keeps equal keys in input order
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
def radix_sort_decimal(a):
"""Sort non-negative integers with LSD radix sort in base 10."""
if not a:
return []
max_val = max(a)
out = list(a)
exp = 1
while max_val // exp > 0:
out = counting_sort_by_key(out, lambda x: (x // exp) % 10, 9)
print(f"after digit exp={exp}: {out}")
exp *= 10
return out
print(radix_sort_decimal([170, 45, 75, 90, 802, 24, 2, 66]))The printed passes match the table:
after digit exp=1: [170, 90, 802, 2, 24, 45, 75, 66]
after digit exp=10: [802, 2, 24, 45, 66, 170, 75, 90]
after digit exp=100: [2, 24, 45, 66, 75, 90, 170, 802]
[2, 24, 45, 66, 75, 90, 170, 802]Implementation with binary digits
Real implementations use a power-of-two radix. Then extracting a digit takes a shift and a mask instead of a division and a modulo. With bits_per_digit = 8, each digit is one byte, b = 256, and a 32-bit key needs at most four passes.
def counting_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..k."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
def radix_sort_lsd(a, bits_per_digit=8):
"""Sort non-negative integers using LSD radix sort."""
if not a:
return []
mask = (1 << bits_per_digit) - 1
max_val = max(a)
out = list(a)
shift = 0
while (max_val >> shift) > 0:
out = counting_sort_by_key(out, lambda x: (x >> shift) & mask, mask)
shift += bits_per_digit
return out
print(radix_sort_lsd([170, 45, 75, 90, 802, 24, 2, 66]))
# [2, 24, 45, 66, 75, 90, 170, 802]
print(radix_sort_lsd([0, 0, 0])) # [0, 0, 0]
print(radix_sort_lsd([300, 1, 65536])) # [1, 300, 65536]Some details of this code:
- The count array has
mask + 1 = 2**bits_per_digitslots. Thekargument is the largest possible digit value,mask, and not the largest key. - The loop stops once no bits of
max_valremain aboveshift. The number of passes therefore depends on the largest key in the data, not on a fixed word size. If every key is 0, the loop runs zero times. The function still returns a copy, which is already sorted. - The lambda reads
shiftwhen it is called, not when it is created. That is safe here becausecounting_sort_by_keycalls the lambda only during the current pass. If you stored these lambdas and called them later, they would all see the finalshift. This is a common Python closure trap. - Each pass allocates a fresh output list. Production code usually allocates two buffers once and swaps between them on each pass. The chapter on cost returns to this point.
Sorting records, not just integers
LSD radix sort moves whole items. It does not rebuild values from counts. That means it can sort records by an integer field just as easily as it sorts bare integers. Pass a key function in, and extract digits from key(item) instead of from item:
def counting_sort_by_key(items, key, k):
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
def radix_sort_records(items, key, bits_per_digit=8):
"""Stable LSD radix sort of records by a non-negative integer key."""
if not items:
return []
mask = (1 << bits_per_digit) - 1
max_key = max(key(it) for it in items)
out = list(items)
shift = 0
while (max_key >> shift) > 0:
out = counting_sort_by_key(out, lambda it: (key(it) >> shift) & mask, mask)
shift += bits_per_digit
return out
orders = [("o1", 1200), ("o2", 35), ("o3", 1200), ("o4", 7), ("o5", 300)]
print(radix_sort_records(orders, key=lambda r: r[1]))
# [('o4', 7), ('o2', 35), ('o5', 300), ('o1', 1200), ('o3', 1200)]The two orders with key 1200 come out as o1 before o3, which is their input order. Every pass is stable, so the radix sort as a whole is stable too. You can use it as one pass of a larger multi-key sort.
Common errors
The other errors that come up most often:
- Processing digits in the wrong order. If you run the same stable passes from most significant to least significant, the last pass wins. The result ends up sorted mainly by the ones digit. On the example input, passes ordered hundreds, tens, ones produce
[170, 90, 2, 802, 24, 45, 75, 66]. The least significant digit must go first. - Too few passes. Computing the digit count from the first element, or from
len(a), instead of frommax(a)leaves the high digits unsorted. Thewhile (max_val >> shift) > 0loop avoids this. - Sizing the count array by key range instead of digit range. Passing
max_valaskgives correct output, but it rebuilds the huge count array that radix sort exists to avoid. - Feeding in negative numbers. In Python,
-3 >> 0 & 255is 253, so negative keys land in high buckets and sort after the positives. A later chapter shows how to shift keys so they start at 0. - Sorting the original list on every pass. Each pass must consume the previous pass's output (
out = counting_sort_by_key(out, ...)). Passingaagain throws away all the earlier work.
Exercises
Exercise
Trace LSD radix sort in base 10 on [329, 457, 657, 839, 436, 720, 355]. Give the array after each of the three passes.
Show answer
After the ones pass: [720, 355, 436, 457, 657, 329, 839]. After the tens pass: [720, 329, 436, 839, 355, 457, 657]. After the hundreds pass: [329, 355, 436, 457, 657, 720, 839].
Exercise
With bitsperdigit=8, how many passes does radixsortlsd make on [256, 3, 10]? How many on [255, 3, 10]? Explain using the loop condition.
Show answer
For [256, 3, 10], maxval is 256. The loop runs at shift 0 (256 > 0) and at shift 8 (256 >> 8 = 1 > 0), then stops at shift 16, so it makes 2 passes. For [255, 3, 10], maxval is 255. The loop runs at shift 0, and at shift 8 it gets 255 >> 8 = 0, so it makes 1 pass. 255 fits in one byte and 256 does not.
Exercise
Someone replaces countingsortbykey in radixsortlsd with a function that groups items into buckets correctly but emits each bucket in reverse input order. Is the final output still sorted? Use the input [2, 1] with bitsper_digit=1.
Show answer
No. With one-bit digits, pass 0 sorts by the low bit. 2 has low bit 0 and 1 has low bit 1, so the output is [2, 1]. Pass 1 sorts by bit 1. 2 has bit 1 set and 1 does not, giving [1, 2], which looks fine. Now try [3, 2]. Pass 0 gives [2, 3]. In pass 1, both have bit 1 set, so they tie, and the reversing bucket emits [3, 2]. That is unsorted. The pass is unstable, so a later tie undoes the order an earlier pass established.