Sub topic 12
MSD Radix Sort: Most Significant Digit First
This chapter assumes you have read the earlier chapters on stable counting sort and LSD radix sort. You should be comfortable with prefix sums used as output positions, with splitting a key into digits using shifts and masks, and with the O(d(n + b)) cost of LSD radix sort. Here, d is the number of digits and b is the radix, which is the number of possible values one digit can take.
LSD radix sort starts at the least significant digit and works toward the most significant one, sorting the whole array on every pass. MSD radix sort goes the other way. It starts with the most significant digit, splits the array into buckets by that digit, and then sorts each bucket separately on the next digit. The result is the same sorted array, but MSD radix sort has a different structure, a different cost profile, and different failure modes.
The Core Idea: Partition, Then Recurse
The most significant digit settles the most order. If two keys differ in their top digit, that digit alone decides which comes first, and no lower digit can change it. MSD radix sort uses this in three steps:
- Run one counting-sort pass on the top digit. This groups the keys into b contiguous buckets, and the buckets are already in the correct order relative to each other.
- Inside each bucket, every key has the same top digit. Only the lower digits are left to decide the order within that bucket.
- Recursively sort each bucket on the next digit down, and stop when a bucket holds one key or when no digits are left.
Each bucket is an independent subproblem, so MSD radix sort has the same shape as quicksort. It partitions first and recurses second. The difference is that quicksort splits into two parts around a pivot, while MSD radix sort splits into up to b parts by digit value.
LSD radix sort has no recursion. It makes d full passes over all n keys, and it depends on stability to keep the work of earlier passes. In MSD radix sort, each recursive call works only on keys that already tie on every higher digit. The order between buckets is final once the bucket is formed, so later passes never need to preserve it.
A Worked Example
Take the keys [170, 45, 75, 90, 802, 24, 2, 66] in base 10, padded to three digits: 170, 045, 075, 090, 802, 024, 002, 066.
The first pass groups the keys by the hundreds digit:
| Hundreds digit | Bucket contents |
|---|---|
| 0 | 045, 075, 090, 024, 002, 066 |
| 1 | 170 |
| 8 | 802 |
Buckets 1 and 8 each hold one key, so they are finished. Bucket 0 still has six keys, so the algorithm sorts it on the tens digit:
| Tens digit | Bucket contents |
|---|---|
| 0 | 002 |
| 2 | 024 |
| 4 | 045 |
| 6 | 066 |
| 7 | 075 |
| 9 | 090 |
Every sub-bucket now holds a single key, so the recursion stops before it ever reads the ones digit. Joining the buckets in order gives 2, 24, 45, 66, 75, 90, 170, 802.
LSD radix sort would have made three full passes over all eight keys. MSD radix sort read the ones digit of none of them. MSD radix sort only reads as many digits as it needs to tell the keys apart, and this property is the main reason to use it.
Implementation
The version below sorts non-negative integers. Each recursive call does one counting-sort pass over the slice a[lo:hi] using the digit at position shift. It then recurses into every bucket that holds more than one key. Small buckets go to insertion sort instead, for reasons covered in the next section.
def msd_radix_sort(a, bits_per_digit=8, cutoff=16):
"""Sort non-negative integers with MSD radix sort. Returns a new list."""
out = list(a)
if len(out) < 2:
return out
total_bits = max(max(out).bit_length(), 1)
num_digits = (total_bits + bits_per_digit - 1) // bits_per_digit
top_shift = (num_digits - 1) * bits_per_digit
_msd(out, 0, len(out), top_shift, bits_per_digit, cutoff)
return out
def _insertion_sort(a, lo, hi):
for i in range(lo + 1, hi):
x = a[i]
j = i - 1
while j >= lo and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def _msd(a, lo, hi, shift, bits, cutoff):
if hi - lo <= cutoff:
# All keys here share their higher digits, so sorting by full value is correct.
_insertion_sort(a, lo, hi)
return
mask = (1 << bits) - 1
b = mask + 1
# counts[d + 1] tallies digit d; after prefix sums, counts[d] is bucket d's start.
counts = [0] * (b + 1)
for i in range(lo, hi):
counts[((a[i] >> shift) & mask) + 1] += 1
for d in range(b):
counts[d + 1] += counts[d]
starts = counts[:] # keep bucket boundaries; counts is consumed below
tmp = [0] * (hi - lo)
for i in range(lo, hi):
d = (a[i] >> shift) & mask
tmp[counts[d]] = a[i]
counts[d] += 1
a[lo:hi] = tmp
if shift == 0:
return # last digit: buckets now hold equal keys
for d in range(b):
s, e = lo + starts[d], lo + starts[d + 1]
if e - s > 1:
_msd(a, s, e, shift - bits, bits, cutoff)
data = [170, 45, 75, 90, 802, 24, 2, 66]
print(msd_radix_sort(data, bits_per_digit=4, cutoff=1))
# [2, 24, 45, 66, 75, 90, 170, 802]
import random
nums = [random.randrange(10**9) for _ in range(20000)]
assert msd_radix_sort(nums) == sorted(nums)
print("ok")Some details in this code are easy to get wrong:
- Alignment of the top digit. The first shift must be a multiple of
bits_per_digitand must cover the highest set bit of the largest key. If you start at a shift that is not aligned, digits overlap or bits are skipped. - Saved bucket boundaries. The placement loop increments
counts, so the code copies the boundaries intostartsbefore that loop. Recursing with the incremented values is a common bug. Those values point at bucket ends, not bucket starts. - The base case at
shift == 0. After the last digit, every key in a bucket is equal, so there is nothing left to sort. - Stability. This version places keys into a temporary buffer in input order, so it is stable. Insertion sort with a strict
>comparison is also stable. If you replace these with an in-place partition, you lose stability.
The Small-Bucket Problem
Each call to _msd allocates and scans a count array of size b, whatever the size of the slice. The recursion splits the data into many buckets, and most of them end up small. With b = 256, sorting a bucket of 5 keys still costs 257 counter slots and a 256-step prefix-sum loop. That fixed overhead is far larger than the actual work.
The total cost can be counted by recursion level. Each level does O(n) work moving keys. It also does O(b) work for every bucket that gets recursed into. In the worst case the number of buckets grows by a factor of b per level until buckets reach size 1. The sum of the per-bucket overhead can then dominate the running time.
There are two standard fixes, and the implementation above uses the first:
- Cutoff to insertion sort. Below a size threshold, typically somewhere from 16 to 64 keys, switch to a simple comparison sort. The keys in a bucket share all higher digits, so the comparison sort only has to order a short list.
- A smaller radix deeper in the recursion. Some implementations use 8-bit digits at the top and smaller digits, or a different algorithm, once buckets shrink.
Cost and Edge Cases
When the keys are spread out, MSD radix sort only examines enough leading digits to separate them. Each key's distinguishing prefix is the shortest prefix that no other key shares. For n random keys in base b, that prefix has about log_b(n) digits, which can be far fewer than d. This matters most when keys are long relative to n, such as 64-bit integers or strings.
The worst case is still O(d(n + b)) for key movement, plus the overhead for buckets. Several inputs push MSD radix sort toward that worst case:
| Input | What happens |
|---|---|
| All keys equal | Every level puts all n keys in one bucket, so the sort does all d passes and never gets the early-termination benefit. |
| Keys sharing a long common prefix | The first few passes do no useful work because every key lands in the same bucket. |
| Skewed distribution, such as small values stored in 64-bit keys | High digits are all zero. Starting at `max(a).bit_length()` instead of a fixed 64 bits avoids this. |
| Many duplicates mixed with distinct keys | Duplicate groups recurse to the last digit, while distinct keys stop early. |
The recursion depth is at most d, so stack overflow is not a concern for fixed-width integers. For long strings, d can be large, and an explicit stack is safer.
Memory use also differs from LSD radix sort. The version above allocates a temporary buffer for each call. A production version allocates one auxiliary array of size n and reuses it at every level. American flag sort goes further. It permutes keys in place using cycle swaps within each bucket and needs only O(b) extra space per level, but it gives up stability.
LSD Versus MSD
| Property | LSD radix sort | MSD radix sort |
|---|---|---|
| Digit order | Least significant first | Most significant first |
| Structure | d full passes in a loop | Recursive partitioning, like quicksort |
| Needs stable inner sort | Yes, for correctness | No. The bucket order is final once formed |
| Reads every digit of every key | Yes | No, only the distinguishing prefix |
| Overhead risk | Low: b counters per pass | High: b counters per bucket, so a cutoff is needed |
| Variable-length keys | Awkward, because keys must be padded | Natural, because a short key ends its own recursion |
| In-place variant | Not practical | American flag sort, which is unstable |
| Code complexity | Simple | Moderate |
Use LSD radix sort for fixed-width integers when you want short, predictable code. Use MSD radix sort when keys are long or vary in length, or when you expect most keys to differ early. Strings are the classic case, and the next chapter adapts this recursion to them.
Exercise
You call the implementation above on 100,000 copies of the integer 4,000,000,000 with bitsperdigit=8. How many counting-sort passes run, and why does MSD radix sort get no early-termination benefit here?
Show answer
4,000,000,000 has a bit_length of 32, so there are 4 digits and 4 passes (shifts 24, 16, 8, 0). At every level all keys land in a single bucket, which is larger than the cutoff, so the code recurses. Equal keys never have a distinguishing prefix, so the algorithm reads every digit, just as LSD radix sort would.
Exercise
In _msd, what goes wrong if the recursion loop uses counts[d] and counts[d + 1] instead of starts[d] and starts[d + 1]?
Show answer
After the placement loop, counts[d] has been incremented once for every key in bucket d, so it holds the end of bucket d, which is also the start of bucket d + 1. Each recursive call would get the wrong slice, offset by one bucket. Keys would be sorted inside the wrong ranges, and the final output could be out of order.
Exercise
Why can MSD radix sort use an unstable in-place partition at each level, while LSD radix sort cannot?
Show answer
In MSD radix sort, keys that end up in the same bucket share every digit examined so far, and lower digits decide their order later in the recursion. No earlier order needs protecting. LSD radix sort relies on each pass keeping the order produced by the previous passes for keys that tie on the current digit, so an unstable pass would undo that earlier work.