Radix Sort: Digit Passes and Cost
Sort by the last digit, then the next, up to the first. Each pass is stable, so it never undoes the order the earlier passes built.
How the Radix Sort Algorithm Works
- Find the largest value; its digit count d is the number of passes
- Stably sort the whole array by the ones digit
- Stably sort it again by the tens digit
- Continue to the most significant digit; the array is now sorted
Radix sort sorts numbers by looking at one digit at a time instead of comparing whole values. The common version, LSD radix sort, starts with the least significant digit (the ones) and works left. After the pass on digit i, the array is sorted by its last i digits.
Each pass is itself a sort on a key with only k possible values, 10 for decimal digits. That is small enough to use a stable counting sort per pass, which takes O(n + k) time.
- Shorter numbers are read with leading zeros: 45 is 045
- k is the base: 10 for decimal, 2 for bits, 256 for bytes
- Works on any key that splits into fixed positions: IDs, dates, fixed-length strings
Example: Sorting 170, 45, 75, 90, 24
The largest value has three digits, so there are three passes. By ones digit: 170, 90, 24, 45, 75. By tens digit: 24, 45, 170, 75, 90 (the last two digits now read 24, 45, 70, 75, 90). By hundreds digit: 24, 45, 75, 90, 170.
In the last pass, four values share hundreds digit 0. They come out in the order pass 2 left them, and that order is already correct on the lower digits.
- Pass 1 (ones): 170, 90, 24, 45, 75
- Pass 2 (tens): 24, 45, 170, 75, 90
- Pass 3 (hundreds): 24, 45, 75, 90, 170
Why Every Pass Must Be Stable
A stable sort keeps equal keys in their existing order. In radix sort that existing order is the result of all earlier passes. When two values tie on the current digit, the earlier passes have already put their lower digits in order, and only a stable pass keeps it.
If a pass is unstable, ties come out in any order and the lower digits are scrambled. Nothing later fixes it, because no later pass looks at those digits again. Quicksort or heapsort per digit therefore gives wrong answers.
The direction matters for the same reason. The last pass decides the final order, so it must use the most significant digit. Running the passes from the left gives an array sorted only by its last digit.
- Stability carries the earlier passes forward
- An unstable pass loses them for good
- The most significant digit must be sorted last
Terms, operations, and practical uses
Terms
- RadixThe base of the number system, and so the number of possible digit values k: 10 for decimal, 256 for bytes.
- LSDLeast significant digit first. d stable passes over the whole array.
- MSDMost significant digit first. Split into groups by the first digit, then recurse into each group.
Costs
- Time O(d(n + k))d passes, each a counting pass over n values and k counters. Same in every case.
- Space O(n + k)An output buffer of n slots and k counters per pass.
- StableYes, as long as every pass is stable.
Pitfalls
- Unstable passScrambles the order built by earlier passes; the result is wrong.
- Wrong directionLSD passes run from the left leave the array sorted by the last digit only.
- Negative valuesBreak the digit formula; sort them separately or shift every key.
Code in Python, C++ and Java
def counting_sort_by_digit(values, place):
counts = [0] * 10
for value in values:
counts[value // place % 10] += 1
# Cumulative counts, so counts[d] is one past the last slot for digit d.
for digit in range(1, 10):
counts[digit] += counts[digit - 1]
output = [0] * len(values)
# Backwards with a pre-decrement, so equal digits keep their order.
for value in reversed(values):
digit = value // place % 10
counts[digit] -= 1
output[counts[digit]] = value
return output
def radix_sort(values):
if not values:
return values
place = 1
while max(values) // place > 0:
values = counting_sort_by_digit(values, place)
place *= 10
return values
print(radix_sort([170, 45, 75, 90, 24]))#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// One stable counting-sort pass, keyed on a single digit.
vector<int> countingSortByDigit(const vector<int>& values, int place) {
vector<int> counts(10, 0);
for (int value : values) counts[value / place % 10]++;
// Cumulative counts, so counts[d] is one past the last slot for digit d.
for (int digit = 1; digit < 10; digit++) counts[digit] += counts[digit - 1];
vector<int> output(values.size());
// Backwards with a pre-decrement, so equal digits keep their order.
for (int i = (int)values.size() - 1; i >= 0; i--) {
int digit = values[i] / place % 10;
counts[digit]--;
output[counts[digit]] = values[i];
}
return output;
}
vector<int> radixSort(vector<int> values) {
if (values.empty()) return values;
int highest = *max_element(values.begin(), values.end());
for (int place = 1; highest / place > 0; place *= 10) {
values = countingSortByDigit(values, place);
}
return values;
}
int main() {
vector<int> sorted = radixSort({170, 45, 75, 90, 24});
cout << "[";
for (size_t i = 0; i < sorted.size(); i++) cout << (i ? ", " : "") << sorted[i];
cout << "]" << endl;
return 0;
}import java.util.Arrays;
public class Main {
// One stable counting-sort pass, keyed on a single digit.
static int[] countingSortByDigit(int[] values, int place) {
int[] counts = new int[10];
for (int value : values) counts[value / place % 10]++;
// Cumulative counts, so counts[d] is one past the last slot for digit d.
for (int digit = 1; digit < 10; digit++) counts[digit] += counts[digit - 1];
int[] output = new int[values.length];
// Backwards with a pre-decrement, so equal digits keep their order.
for (int i = values.length - 1; i >= 0; i--) {
int digit = values[i] / place % 10;
counts[digit]--;
output[counts[digit]] = values[i];
}
return output;
}
static int[] radixSort(int[] values) {
if (values.length == 0) return values;
int highest = Arrays.stream(values).max().getAsInt();
for (int place = 1; highest / place > 0; place *= 10) {
values = countingSortByDigit(values, place);
}
return values;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(radixSort(new int[]{170, 45, 75, 90, 24})));
}
}Step through it
Running on [170, 45, 75, 90, 24]
Radix Sort Time Complexity
Each pass costs O(n + k): one sweep to count digits, one over the k counters, one to place values. With d passes the total is O(d(n + k)). When d and k are fixed, as with 32-bit integers, that is O(n). Extra space is O(n + k) for the output array and counters. Best, average and worst cases are the same, because the input order does not change the work.
This does not break the O(n log n) lower bound for sorting; that bound covers algorithms that compare pairs of values, and radix sort never does.
The base trades d against k. For one million 32-bit values, base 10 needs 10 passes; base 256 (one byte per pass) needs 4 with 256 counters; base 65,536 needs only 2, but 65,536 counters per pass stop fitting in fast cache. Bytes are the usual choice.
- Time O(d(n + k)) in every case
- Space O(n + k); not in place
- Larger base: fewer passes, more counters
LSD vs MSD Radix Sort
MSD radix sort goes the other way: it splits the array by the most significant digit into groups and then sorts each group recursively on the next digit. Groups never mix again, so the passes do not need to be stacked, and a group of one value can stop early.
That makes MSD the natural choice for strings of different lengths, where reading every position would be wasted work. LSD is simpler and faster for fixed-width integers.
| LSD | MSD | |
|---|---|---|
| First digit used | Least significant | Most significant |
| Structure | d full passes over the array | Split into groups, recurse on each |
| Needs stable passes | Yes | Only for a stable result |
| Can stop early | No, always d passes | Yes, once a group has one value |
| Best fit | Fixed-width integers | Variable-length strings |
- LSD: every value goes through every pass
- MSD: recursion lets distinct prefixes finish early
When to Use It, and Edge Cases
Radix sort pays off for large n with short keys: millions of 32-bit or 64-bit integers, fixed-length IDs, dates as YYYYMMDD. For small arrays, or keys with many digits relative to log n, a good comparison sort is usually faster in practice because radix sort moves every value through a buffer on each pass.
The usual code assumes non-negative integers. A negative value gives a negative digit in C++ and Java (an out-of-range index) and a wrong digit in Python, where −45 is read as 955. Fix it by sorting negatives separately and reversing them, or by adding the size of the smallest value to every key first. Floating-point values can be radix sorted after flipping their bit patterns so that the integer order matches the numeric order.
- Good: many short integer keys
- Poor: small n, long keys, or general comparison-based data
- Negatives and floats need a key transform first