Algorithms · Visualized
Radix Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Radix Sort sorts numbers digit by digit, starting from the least significant digit (rightmost) and moving to the most significant. Time: O(d × (n + k)) average, O(d × (n + k)), where d = number of digits, k = base (usually 10) worst; space: O(n + k).
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Radix Sort
SortingRadix Sort sorts numbers digit by digit, starting from the least significant digit (rightmost) and moving to the most significant. At each digit position it uses a stable sort (usually Counting Sort) to order the numbers based on just that digit, and because each pass is stable, the order from previous passes is preserved.
How Radix Sort Works
- Find the maximum number in the array to know how many digits you need to process.
- Starting with the least significant digit (units place), sort all numbers based on that digit using a stable sort like counting sort.
- Move to the next digit (tens place) and stable-sort again — numbers with equal tens digits keep their previous relative order.
- Repeat for hundreds, thousands, and so on, until you've processed the most significant digit of the largest number.
- After the final pass, the array is fully sorted.
Radix Sort Worked Example
Input: [170, 45, 75, 90, 802, 24, 2, 66]
Sort by units digit: [170,90,802,2,24,45,75,66]. Sort by tens digit (stable): [802,2,24,45,66,170,75,90]. Sort by hundreds digit (stable): [2,24,45,66,75,90,170,802]. Fully sorted after 3 passes (matching the 3-digit max, 802).
def radix_sort(a):
def counting(a, exp):
cnt = [0] * 10
out = [0] * len(a)
for v in a:
cnt[(v // exp) % 10] += 1
for i in range(1, 10):
cnt[i] += cnt[i - 1]
for v in reversed(a):
d = (v // exp) % 10
cnt[d] -= 1
out[cnt[d]] = v
return out
exp = 1
m = max(a)
while m // exp > 0:
a = counting(a, exp)
exp *= 10
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Radix Sort Time & Space Complexity
When to Use Radix Sort
- Sorting large lists of integers or fixed-length strings quickly, faster than comparison sorts for the right data.
- Sorting things like phone numbers, postal codes, or IDs with a fixed number of digits.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.