Radix Sort
Radix Sort
Radix sort is a non-comparison sorting algorithm that sorts integers by processing individual digits. Instead of comparing elements against each other, it distributes elements into buckets based on each digit, from the least significant digit (LSD) to the most significant digit (MSD). This allows it to sort in O(nk) time, where k is the number of digits — potentially faster than comparison-based sorts for certain inputs.
How It Works
- Find the maximum number to determine how many digit positions to process
- Starting from the least significant digit (ones place):
- Distribute all elements into 10 buckets (0-9) based on the current digit
- Collect elements from buckets in order (0 first, then 1, ..., then 9)
- Move to the next digit position (tens, hundreds, ...) and repeat
- After processing all digit positions, the array is sorted
The algorithm relies on a stable distribution step — elements with the same digit maintain their relative order from the previous pass. This is why sorting from LSD to MSD works correctly.
Step-by-Step Example
Given [170, 45, 75, 90, 802, 24, 2, 66]:
Pass 1 — ones digit:
- Bucket 0: 170, 90
- Bucket 2: 802, 2
- Bucket 4: 24
- Bucket 5: 45, 75
- Bucket 6: 66
- Collect:
[170, 90, 802, 2, 24, 45, 75, 66]
Pass 2 — tens digit:
- Bucket 0: 802, 2
- Bucket 2: 24
- Bucket 4: 45
- Bucket 6: 66
- Bucket 7: 170, 75
- Bucket 9: 90
- Collect:
[802, 2, 24, 45, 66, 170, 75, 90]
Pass 3 — hundreds digit:
- Bucket 0: 2, 24, 45, 66, 75, 90
- Bucket 1: 170
- Bucket 8: 802
- Collect:
[2, 24, 45, 66, 75, 90, 170, 802]✓
Code Snippet
def radix_sort(numbers: list[int]) -> list[int]:
"""Sort non-negative integers by processing digits from LSD to MSD."""
if not numbers:
return numbers
max_value = max(numbers)
digit_position = 1 # Start with ones place
while digit_position <= max_value:
# Create 10 buckets (one per digit 0-9)
buckets = [[] for _ in range(10)]
# Distribute elements into buckets based on current digit
for number in numbers:
digit = (number // digit_position) % 10
buckets[digit].append(number)
# Collect elements from buckets in order
numbers = []
for bucket in buckets:
for number in bucket:
numbers.append(number)
digit_position *= 10
return numbers
Here's an alternative using counting sort as the stable subroutine (more memory-efficient):
def radix_sort_counting(numbers: list[int]) -> list[int]:
"""Radix sort using counting sort for each digit pass."""
if not numbers:
return numbers
max_value = max(numbers)
digit_position = 1
while digit_position <= max_value:
output = [0] * len(numbers)
count = [0] * 10
# Count occurrences of each digit
for number in numbers:
digit = (number // digit_position) % 10
count[digit] += 1
# Compute cumulative counts (positions)
for i in range(1, 10):
count[i] += count[i - 1]
# Build output array (traverse input in reverse for stability)
for i in range(len(numbers) - 1, -1, -1):
digit = (numbers[i] // digit_position) % 10
count[digit] -= 1
output[count[digit]] = numbers[i]
numbers = output
digit_position *= 10
return numbers
Complexity Analysis
Time Complexity: O(nk)
nis the number of elementskis the number of digits in the maximum value (k = log₁₀(max_value) + 1)- Each pass processes all n elements in O(n) time
- There are k passes total
For fixed-size integers (e.g., 32-bit), k is a constant, making radix sort effectively O(n). When values can be arbitrarily large (k = O(log n)), radix sort becomes O(n log n), matching comparison sorts.
Space Complexity: O(n + k)
The bucket-based version requires O(n) space for the output array plus O(k) for the 10 buckets (where k=10 for decimal digits). Total auxiliary space is O(n + 10) = O(n).
When to Use Radix Sort
- Sorting integers with bounded range: When the maximum number of digits k is small relative to n, radix sort outperforms comparison sorts.
- Fixed-length strings: Radix sort generalizes naturally to strings of equal length (sort by each character position).
- Large datasets of short keys: Sorting millions of ZIP codes, phone numbers, or social security numbers.
- Parallel/distributed sorting: Each bucket pass is highly parallelizable.
When to Avoid It
- Floating-point numbers: Requires special encoding to handle sign bits and exponents correctly.
- Variable-length strings: MSD radix sort handles this but adds complexity.
- Small datasets: The overhead of multiple passes and bucket allocation isn't worth it for small n.
- Large key space: If numbers have many digits (k is large), comparison sorts may win.
Radix Sort vs. Comparison Sorts
| Algorithm | Time | Space | Comparison-based? |
|---|---|---|---|
| Radix Sort | O(nk) | O(n+k) | No |
| Quicksort | O(n log n) avg | O(log n) | Yes |
| Merge Sort | O(n log n) | O(n) | Yes |
The theoretical lower bound for comparison sorts is Ω(n log n). Radix sort bypasses this by not comparing elements directly — it uses digit extraction instead.
Key Properties
| Property | Value |
|---|---|
| In-place | No (requires O(n) auxiliary space) |
| Stable | Yes (when using stable distribution) |
| Adaptive | No |
| Non-comparative | Yes |