Radix Sort in Data Structure — Algorithm, Working and Complexity
Radix Sort is a non-comparison-based sorting algorithm that sorts integers by processing individual digits, starting from the least significant digit (LSD) to the most significant digit (MSD), using a stable sort (typically Counting Sort) at each digit position.
Working
- Find the maximum number to determine the number of digits to process.
- For each digit position (starting from the ones place), perform a stable sort of the entire array based on that digit.
- Repeat for each subsequent digit position until the most significant digit has been processed.
def counting_sort_by_digit(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for num in arr:
count[(num // exp) % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for num in reversed(arr):
digit = (num // exp) % 10
count[digit] -= 1
output[count[digit]] = num
return output
def radix_sort(arr):
max_val = max(arr)
exp = 1
while max_val // exp > 0:
arr = counting_sort_by_digit(arr, exp)
exp *= 10
return arr
Complexity
| Metric | Value |
|---|---|
| Time | O(d * (n + k)) |
| Space | O(n + k) |
Here d is the number of digits in the largest number, n is the number of elements, and k is the base used (usually 10). When d is small relative to log n, Radix Sort can outperform comparison-based sorts.
Applications
- Sorting large collections of integers with a bounded number of digits.
- Sorting fixed-width keys such as phone numbers or IDs.
- A component in suffix array and string sorting algorithms.
Dry Run on [170, 45, 75, 90, 802, 24, 2, 66]
Following one full example makes the digit-by-digit idea concrete. The largest value, 802, has three digits, so there are three passes.
| Pass | Digit used | Array after the stable sort |
|---|---|---|
| 1 | Ones (exp = 1) | 170, 90, 802, 2, 24, 45, 75, 66 |
| 2 | Tens (exp = 10) | 802, 2, 24, 45, 66, 170, 75, 90 |
| 3 | Hundreds (exp = 100) | 2, 24, 45, 66, 75, 90, 170, 802 |
Look at pass 1: 170 and 90 both end in 0, and they keep their original order (170 came first). In pass 2, 802 and 2 both have a tens digit of 0, so 802 stays ahead of 2. Only in pass 3 does the hundreds digit finally move 802 to the end. Numbers with fewer digits are treated as if they had leading zeros.
Why Each Pass Must Be Stable
Radix sort works because each pass keeps the order created by the earlier, less significant passes whenever two digits tie. If the inner sort were not stable, pass 3 could put 66 before 45 simply because both have a hundreds digit of 0, and the work done in pass 2 would be lost. That is why the counting sort subroutine walks the input in reverse when placing items: it keeps equal keys in their existing order.
Handling Negative Numbers and Choosing a Base
The basic version assumes non-negative integers. A simple fix is to split the input, sort the absolute values of the negatives separately, then reverse and negate them:
def radix_sort_signed(arr):
negatives = [-x for x in arr if x < 0]
positives = [x for x in arr if x >= 0]
neg_sorted = radix_sort(negatives) if negatives else []
pos_sorted = radix_sort(positives) if positives else []
return [-x for x in reversed(neg_sorted)] + pos_sorted
print(radix_sort_signed([15, -3, 0, -42, 7])) # [-42, -3, 0, 7, 15]
The base does not have to be 10. Low-level implementations often use base 256 and treat each byte of the key as one digit. A larger base means fewer passes but a bigger count array, so it is a trade-off between time and memory.
LSD versus MSD
- LSD (least significant digit first) is what the code above does. It is simple and suits fixed-length keys like IDs.
- MSD (most significant digit first) splits data into buckets by the leading digit and sorts each bucket recursively. It suits variable-length strings and can stop early once a bucket has one item.
When to Pick Radix Sort, and Common Slip-Ups
Choose it for large volumes of integers or fixed-width keys where the number of digits is small. Prefer a comparison sort such as merge sort or the built-in sort when keys are floating-point numbers, complex objects, or very long and varied, because the extra passes and memory then outweigh the benefit.
- Calling
max()on an empty list crashes; check for empty input first. - Using an unstable sort for a digit pass gives wrong results without any error.
- Forgetting that radix sort needs extra output space, so it is not in-place.
Remember: number of passes equals digits in the largest key, each pass is a stable counting sort, and ties always keep their previous order.