Sub topic 12
MSD Radix Sort: Most Significant Digit First
This chapter assumes you already know LSD radix sort from the earlier chapters: keys are split into fixed-width digits, and each digit is sorted with a stable counting sort. You should also be comfortable reading recursive Python functions.
LSD radix sort starts with the least significant digit and sweeps the whole array once per digit. MSD radix sort starts with the most significant digit. It splits the input into buckets by that digit and then sorts each bucket on its own, using the next digit.
The working model
The first digit already decides most of the final order. Every key whose top digit is 0 comes before every key whose top digit is 1, whatever the remaining digits are. So once you split the input on the top digit, the buckets never need to interact again. Each bucket becomes a smaller, independent sorting problem on the remaining digits.
The algorithm has four steps:
- Distribute the keys into buckets by the current digit.
- Recursively sort each bucket using the next digit to the right.
- Concatenate the buckets in digit order.
- Stop recursing when a bucket has at most one key or no digits are left.
The diagram uses decimal digits to show this on the same numbers as the LSD chapter, padded to three digits.
In this example the units digit is never examined. LSD radix sort would have run three full passes over all eight keys. MSD radix sort stops as soon as each bucket holds one key.
An implementation
The version below works on non-negative integers and uses bit-sized digits. Small buckets go to insertion sort, because allocating 2^b empty buckets to sort five keys wastes time.
def insertion_sort(a):
for i in range(1, len(a)):
x = a[i]
j = i - 1
while j >= 0 and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
return a
def _msd(a, shift, bits, cutoff):
if len(a) <= 1 or shift < 0:
return a # one key, or all digits used: keys are equal
if len(a) <= cutoff:
return insertion_sort(a)
mask = (1 << bits) - 1
buckets = [[] for _ in range(mask + 1)]
for x in a: # appending keeps equal digits in input order
buckets[(x >> shift) & mask].append(x)
out = []
for b in buckets:
if b:
out.extend(_msd(b, shift - bits, bits, cutoff))
return out
def msd_radix_sort(a, bits_per_digit=8, cutoff=16):
"""Sort non-negative integers, most significant digit first."""
if not a:
return []
top_bit = max(max(a).bit_length(), 1) - 1
top_shift = (top_bit // bits_per_digit) * bits_per_digit
return _msd(list(a), top_shift, bits_per_digit, cutoff)
print(msd_radix_sort([170, 45, 75, 90, 802, 24, 2, 66], bits_per_digit=4, cutoff=0))
# [2, 24, 45, 66, 75, 90, 170, 802]In this code, top_shift aligns the first digit so that it contains the highest set bit of the largest key. Each recursive call moves one digit to the right by subtracting bits from shift.
How it differs from LSD
| Aspect | LSD radix sort | MSD radix sort |
|---|---|---|
| Digit order | Rightmost first | Leftmost first |
| Structure | Fixed loop of d full passes | Recursion on buckets |
| Needs stable passes for correctness | Yes | No, buckets never mix |
| Can stop early | No, all digits always processed | Yes, once buckets are small or unique |
| Variable-length keys | Awkward, needs padding | Natural, a short key ends its recursion |
| Overhead | Low and predictable | Many small buckets, recursion cost |
MSD radix sort is the usual choice for strings. The first character splits the input, and a string that runs out of characters is placed ahead of every longer string that shares its prefix. A later chapter covers this.
Exercise
You MSD-sort one million 32-bit integers with 8-bit digits, and every key starts with the same top byte. What happens on the first call, and why does this not break correctness?
Show answer
All one million keys land in a single bucket, so the first pass does a full distribution without dividing the problem. The algorithm then recurses on that bucket with the next byte. The result is still correct, because a shared top digit says nothing about the order and the remaining digits decide it. The only cost is one wasted pass plus the 256-bucket overhead.
Exercise
In the code, why does _msd return a unchanged when shift < 0, even if the bucket has many keys?
Show answer
A negative shift means every digit has been used. All keys in the bucket matched on every digit, so they are equal and already in sorted order.