Sort fixed width keys by processing digits from least significant to most significant using a stable inner sort.
LSD radix sort sorts keys by scanning digit positions from right to left, starting with the least significant digit. Each pass uses a stable sorting method on one digit position.
The usual inner method is stable counting sort. Stability is essential because later passes must preserve the order already established by earlier, less significant digits.
Problem
Given keys of fixed width , where each digit is in range , sort the keys in increasing order.
A key has the form:
LSD radix sort processes:
Algorithm
lsd_radix_sort(A, m, b):
for p from 0 to m - 1:
stable_counting_sort_by_digit(A, p, b)
return AExample
Sort:
After ones digit:
After tens digit:
After hundreds digit:
Correctness
After pass , the array is sorted by the suffix of digits:
The base case holds after sorting by . For the induction step, stable sorting by groups elements by the new digit while preserving the order of lower digits inside each group. Therefore the array becomes sorted by digits through .
After the final pass, every digit has been considered, so the array is sorted by the full key.
Complexity
Each digit pass costs:
For digit positions, total time is:
Space:
For fixed width integers and a fixed byte base, this is linear in .
When to Use
Use LSD radix sort when:
- keys have fixed width
- digit extraction is cheap
- stable counting sort is available
- the digit alphabet is small
- sorting many integers or fixed length strings
It is less natural for variable length strings unless they are padded or handled with a sentinel digit.
Implementation
def lsd_radix_sort(a, digits, base=10):
for p in range(digits):
a = counting_sort_digit(a, p, base)
return a
def counting_sort_digit(a, p, base):
count = [0] * base
divisor = base ** p
for x in a:
digit = (x // divisor) % base
count[digit] += 1
for i in range(1, base):
count[i] += count[i - 1]
out = [0] * len(a)
for i in range(len(a) - 1, -1, -1):
x = a[i]
digit = (x // divisor) % base
count[digit] -= 1
out[count[digit]] = x
return out