Radix Sort
Sort non-negative integers one decimal digit at a time, starting with the ones digit.
Given an array arr
Example
Output: [2, 24, 45, 66, 75, 90, 170, 802]
The Idea
Imagine a pile of numbered tickets and ten trays in front of you, labelled 0 to 9. You are not allowed to hold two tickets side by side and compare them. You may only read one digit of a ticket and drop it into the tray with that digit. Can trays alone put the pile in order?
Take the example. Its largest number, 802, has three digits, so write every number with three digits: 45 becomes 045 and 2 becomes 002. Now drop each number into a tray by its last digit, the ones digit, and stack the trays back up from tray 0 to tray 9. The pile now reads 170, 90, 802, 2, 24, 45, 75, 66.
That is in order by the ones digit only, so do it again with the tens digit, and then with the hundreds digit. But wait: when the tens pass reshuffles the pile, does it throw away the work of the ones pass?
The picture below answers that with the example. Each row is the pile after one pass, and the digit that pass sorts by is orange.
In the row labelled "by tens digit", 170 and 75 both have tens digit 7, so they land in the same tray, boxed in teal. Inside that tray they keep the order they had in the row above, where 170 came first because its ones digit, 0, is smaller than 5. So the tens pass sorts by the tens digit, and ties are already in ones-digit order. After it, the pile is sorted by the last two digits: 02, 02, 24, 45, 66, 70, 75, 90.
The hundreds pass does the same one level up. In the last row, every number except 170 and 802 has hundreds digit 0, and those keep the order of the tens row, so the whole pile comes out sorted.
Everything rests on that one rule: a pass keeps numbers with the same digit in the order the previous pass left them. A sort that keeps equal keys in their earlier order is called stable. Sorting by digits this way is called radix sort, since radix is another word for the base of a number system, 10 here. Starting from the ones digit, the digit that changes a number's value the least, makes it a least significant digit (LSD) radix sort.
Solution Approach
Three decisions turn the trays into code: how many passes to make, how to read one digit of a number, and how one pass sorts by that digit while keeping ties in order.
How many passes
When can the passes stop? Once a digit position is past the largest number's digits, every number has a 0 there, and a stable pass changes nothing. So the number of passes is the number of digits in the largest value: three for 802.
The code keeps a multiplier expmax / exp802 / 1000exp
Why is explongintexpmax / expintint
Reading one digit
How do we get the tens digit of 802 without turning it into text? Dividing by exp% 10exp802 / 1080 % 10(v / exp) % 10
One stable pass with counting
How does one pass put numbers into trays without ten separate lists? It counts first. In the ones pass, two numbers end in 0 (170 and 90), two end in 2 (802 and 2), one in 4, two in 5 and one in 6. Adding the counts up from digit 0 tells where each tray ends in the result: the numbers ending in 0 fill positions 0 and 1, and those ending in 2 fill positions 2 and 3.
Then the pass walks the array from back to front and puts each number into the last free position of its tray. It meets 2 before 802, because 2 comes later in the input, so 2 takes position 3 and 802 takes position 2. Going backwards, the later number takes the later slot, and the tray keeps the input order. This way of sorting by counting keys is
Java Solution
The method sort
- First, if
is empty, return, because there is no largest value to find.arr - Find the largest value,
, withmax .Arrays.stream(arr).max() - Loop with the
multiplierlong from 1, multiplying it by 10 each time, whileexp is above 0. Each turn calls the helper methodmax / exp , which does one stable pass by the digitsortByDigit(arr, exp) picks, in the next three steps.exp - Inside
, a loop oversortByDigit fills an arrayarr of 10 entries:count becomes how many numbers have digit d.count[d] - A second loop adds to each entry the one before it, turning the counts into running totals. Now each entry of
is the position just after the last number with that digit.count - A third loop walks
from back to front. For each number it lowers the entry for its digit by one and puts the number at that position in a new array,arr . Finallyoutput copiesSystem.arraycopy back intooutput .arr
The mainInteger.MAX_VALUE
import java.util.Arrays;
public class RadixSort {
// Sorts non-negative ints, one decimal digit at a time, ones digit first
public static void sort(int[] arr) {
if (arr.length == 0) {
return;
}
int max = Arrays.stream(arr).max().getAsInt();
for (long exp = 1; max / exp > 0; exp *= 10) { // exp is 1, 10, 100, ...
sortByDigit(arr, (int) exp);
}
}
// One pass: a stable counting sort on the digit (value / exp) % 10
static void sortByDigit(int[] arr, int exp) {
int[] count = new int[10];
for (int v : arr) {
count[(v / exp) % 10]++; // how many numbers have each digit
}
for (int digit = 1; digit < 10; digit++) {
count[digit] += count[digit - 1]; // where each digit's group ends
}
int[] output = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) { // backwards keeps it stable
output[--count[(arr[i] / exp) % 10]] = arr[i];
}
System.arraycopy(output, 0, arr, 0, arr.length);
}
public static void main(String[] args) {
int[] data = {170, 45, 75, 90, 802, 24, 2, 66};
String[] names = {"ones", "tens", "hundreds"};
for (int p = 0, exp = 1; p < 3; p++, exp *= 10) { // the three passes, one by one
sortByDigit(data, exp);
System.out.println("by " + names[p] + " digit: " + Arrays.toString(data));
}
int[][] tests = {
{170, 45, 75, 90, 802, 24, 2, 66},
{},
{5},
{3, 1, 3, 0, 1},
{0, 0, 0},
{Integer.MAX_VALUE, 0, 1000000000, 999999999, 7},
};
for (int[] t : tests) {
sort(t);
System.out.println(Arrays.toString(t));
}
}
}
Running it prints:
by ones digit: [170, 90, 802, 2, 24, 45, 75, 66]
by tens digit: [802, 2, 24, 45, 66, 170, 75, 90]
by hundreds digit: [2, 24, 45, 66, 75, 90, 170, 802]
[2, 24, 45, 66, 75, 90, 170, 802]
[]
[5]
[0, 1, 1, 3, 3]
[0, 0, 0]
[0, 7, 999999999, 1000000000, 2147483647]
The first three lines match the rows of the picture. In the line starting "by tens digit", 170 is still right before 75, and in the next line every number is in place. The fourth line, the full sort
The array of zeros prints [0, 0, 0]max / 1
Why does the third loop go backwards? A run with only that loop changed to go front to back sorted the example into [90, 75, 66, 45, 24, 2, 170, 802]
The method also needs non-negative input, as the problem says. In Java, -1 / 1 % 10[3, -1, 2]ArrayIndexOutOfBoundsExceptioncount[-1]
So the sort is stable, as each pass must be. It is not in place: every pass builds the extra array output
Complexity
Every pass reads each number twice and writes it twice, so the cost depends on n, the number of values, and on how many passes the largest value needs.
- Best time: O(n), because when every value has one digit, as in
, a single pass sorts the array, which a counting run confirmed.[9, 3, 7, 1, 5] - Worst time: O(n) with ten passes, because one ten-digit value such as
forces ten passes over all n numbers, and noInteger.MAX_VALUE has more digits.int - Average time: O(k ยท n), where k is the number of digits in the largest value, because the order of the input never changes the work: sorted, reversed or shuffled, the passes do the same steps.
- Space: O(n), because each pass makes the array
of n numbers and the arrayoutput of 10 entries.count
Radix sort needs integer keys that split into digits. For negative numbers or values without digits, a comparison sort such as