Sub topic 9
LSD Radix Sort: Least Significant Digit First
This chapter assumes you already have the stable counting_sort_by_key from earlier in the tutorial. It also assumes you know how a key splits into digits, and that you can read bitwise shifts and masks in Python. Here you put those pieces together into a complete sorting algorithm.
The Idea
Counting sort is fast only when the key range k is small. A 32-bit integer has a range of about four billion, so a count array for the whole key is too large. LSD radix sort handles this by sorting on one small digit at a time. Each digit has a small range, for example 0 to 255 for an 8-bit digit, so every pass is a cheap counting sort.
LSD stands for least significant digit. The algorithm sorts by the rightmost digit first and finishes with the leftmost one. Each pass must be stable, so records with equal digits keep the order the previous pass gave them.
A Hand Trace in Base 10
Decimal digits are easier to follow by eye, so this trace sorts [170, 45, 75, 90, 802, 24, 2, 66] in base 10.
| Pass | Digit used | Result after pass |
|---|---|---|
| 1 | ones | 170, 90, 802, 2, 24, 45, 75, 66 |
| 2 | tens | 802, 2, 24, 45, 66, 170, 75, 90 |
| 3 | hundreds | 2, 24, 45, 66, 75, 90, 170, 802 |
Look at pass 2. Both 802 and 2 have tens digit 0. Pass 1 put 802 before 2, and the stable pass keeps it there. In pass 3, all of 2, 24, 45, 66, 75, and 90 have hundreds digit 0. They stay in the order pass 2 produced, which is already correct for their lower digits. The next chapter proves that this always works.
The Implementation
The code below uses binary digits that are bits_per_digit bits wide instead of decimal ones. To extract a digit it shifts and masks, which is cheaper than dividing and taking a remainder. The block includes the stable counting sort so you can run it as shown.
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]A few details matter here:
maskis both the bit mask and the largest digit value, so it becomes thekargument for the counting sort.- The loop stops once
max_val >> shiftreaches 0. At that point no element has any nonzero bits left. An all-zero input needs no passes. - The lambda reads
shiftwhen it is called. Eachcounting_sort_by_keycall runs to completion beforeshiftchanges, so every pass sees the right value.
Common Errors
- An unstable per-digit sort. If a pass reorders equal digits, the order set by the earlier passes is lost and the final output is wrong.
- Sorting from the most significant digit first with this same loop. The last pass decides the final order, so it must use the most significant digit.
- Negative inputs. In Python,
x >> shifton a negative number never reaches 0, and the digits do not sort in the right order. A later chapter covers how to handle signed keys.
Exercise
With the default bitsperdigit=8, how many counting-sort passes does radixsortlsd make on [170, 45, 75, 90, 802, 24, 2, 66]?
Show answer
Two. max_val is 802. 802 >> 0 = 802 > 0, so the first pass runs. 802 >> 8 = 3 > 0, so the second pass runs. 802 >> 16 = 0, so the loop stops.
Exercise
Suppose each pass used a sort that groups digits correctly but reverses the order of equal digits. Give two numbers that would come out in the wrong order in base 10.
Show answer
Take 12 and 15. Pass 1 on the ones digit gives 12, 15. In pass 2, both have tens digit 1, so the reversing sort outputs 15, 12, which is wrong.