Radix Sort in Java
Learn how Radix Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Radix Sort is a non-comparison sort for integers. Instead of comparing whole values, it sorts them one digit at a time, starting with the ones digit, then the tens, then the hundreds, until it has used every digit of the largest value.
Three ideas carry the whole algorithm:
- Digit pass: one pass sorts the values by a single digit, using a counting sort with ten slots, one for each digit 0 to 9.
- Least significant digit first: the passes go from the rightmost digit to the leftmost, so the most important digit is sorted last.
- Stability: each pass keeps values with the same digit in the order the previous pass left them. That is what makes the earlier, less important digits break the ties of the later ones.
Radix sort is older than computers: punched-card sorting machines in the early 20th century sorted card decks one column at a time, in exactly this order. It runs in linear time for fixed-width keys, so it is a good fit for large amounts of integers, IDs, dates or fixed-length strings, and it is used in GPU sorting and in database engines.
This article uses an LSD (least significant digit) radix sort in base 10: one counting sort per decimal digit, each written to an output array and copied back.
Performance Characteristics
Radix Sort never compares two values with each other, so its speed doesn’t depend on their order, only on how many values there are and how many digits the largest one has.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
In the table, $n$ is the number of values, $d$ is the number of digits of the largest value, and $b$ is the base, here 10.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(d(n + b))$ | Any input: every value is processed once per digit |
| Average | $O(d(n + b))$ | Any input |
| Worst | $O(d(n + b))$ | Any input, but slow when one large value adds many digits |
Why $d(n + b)$? Each of the $d$ passes is a counting sort: it reads every value twice and writes it twice ($n$ work), and creates and sums a count array of $b$ slots. For int values, $d$ is at most 10, so for large $n$ the sort is effectively linear.
One large value sets the number of passes for everyone. Sorting a million values below 100, plus a single 1,000,000,000, takes ten passes instead of two. For a wide range, a larger base such as 256 (one byte at a time) cuts the number of passes, at the cost of a bigger count array.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(n + b)$: the output array and the count array, reused for every pass |
| In place | No (each pass writes to an output array, which is then copied back) |
| Stable | Yes (every digit pass is a stable counting sort) |
Algorithm (Pseudo Code)
Radix Sort starts with the ones digit. It counts how many values end in 0, in 1, and so on up to 9, and turns those counts into running totals, so each digit knows where its group ends in the output. It then walks the values from the back to the front and places each one at the end of its digit’s group. After this pass, the values are grouped by their ones digit, and within a group they keep their earlier order.
The next pass does the same with the tens digit, then the hundreds digit, and so on, until every digit of the largest value has had a pass. Shorter values simply have a digit of 0 in the higher positions. Because each pass is stable, values with the same tens digit stay sorted by their ones digit, values with the same hundreds digit stay sorted by their last two digits, and after the last pass the whole array is in order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sort(array):
checkForNegativeInput(array)
max = largest value
for i = 0, exp = 1 while i < numberOfDigits(max); i++, exp *= 10:
countingSortByDigit(array, exp)
countingSortByDigit(array, exp):
count = new int[10]
for each value: count[(value / exp) % 10]++
for i = 1 to 9: count[i] += count[i - 1]
output = new int[n]
for i = n - 1 down to 0:
digit = (array[i] / exp) % 10
output[count[digit] - 1] = array[i]
count[digit]--
copy output into array
After the pass for exp, the array is sorted by its last log10(exp) + 1 digits: by the ones digit after the first pass, by the last two digits after the second, and so on.
Sorting from the least significant digit first sounds backwards, but it is what makes the simple version work. Each pass only has to be stable, not aware of the previous digits. An MSD (most significant digit first) radix sort exists too, but it has to split the values into groups and sort each group separately.
Visualization
The visualization below follows the Java code line by line, starting with ten values between 2 and 802.
Radix Sort needs values with several digits, so instead of the values 0 to 9, the visualization starts with [170, 45, 75, 90, 802, 24, 2, 66, 351, 9]. The largest value has three digits, so there are three passes.
Each step shows the array, the count array, the output and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with new random values between 0 and 999.
- Digits: every value is shown with as many digits as the largest one; the faint leading zeros are the digits a shorter value doesn’t have. The underlined digit is the one the current pass sorts by.
- Rows: the top row is
array, the middle row thecountarray for the digits 0 to 9, and the bottom row theoutputof the current pass. - Pointer: I is
iinbuildOutput, walking the array from the back. - Colours: the value being read is amber, the cell being written is salmon, and values placed in the output, or copied back after a pass, are green.
Java Code
The implementation is a RadixSort utility class: it is final, has a private constructor, and offers one public static method, sort, for int arrays. The base is the constant BASE = 10. checkForNegativeInput rejects negative values, radixSort runs one pass per digit, and numberOfDigits works out how many passes are needed. Each pass is countingSortByDigit, which is split into four small steps: countDigits, accumulateCounts, buildOutput and copyOutput, with getDigit to read a single digit. The class doesn’t use the SortUtils helpers.
The complete code is in the algorithm-examples repository on GitHub:
RadixSort.java.
sort
1
2
3
4
5
6
7
8
9
public static int[] sort(int[] array) {
if (array.length == 0) {
return array;
}
checkForNegativeInput(array);
radixSort(array);
return array;
}
sort is the entry point. An empty array comes straight back. Otherwise the values are checked, sorted with radixSort, and the same array is returned. Unlike the Counting Sort class, RadixSort copies the result of every pass back, so the input array itself ends up sorted.
checkForNegativeInput
1
2
3
4
5
6
7
private static void checkForNegativeInput(int[] array) {
for (int number : array) {
if (number < 0) {
throw new IllegalArgumentException("Array contains non-positive integers.");
}
}
}
checkForNegativeInput throws an IllegalArgumentException as soon as it finds a negative value. That check is needed: in Java, -25 % 10 is -5, so getDigit would return a negative digit and count[digit] would throw an ArrayIndexOutOfBoundsException.
The exception message says “non-positive integers”, but zero is allowed; only negative values are rejected. A common way to support negative values is to sort them separately, or to flip the sign bit so that they come before the positive values.
radixSort and numberOfDigits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static void radixSort(int[] array) {
final int max = Arrays.stream(array).max().getAsInt();
for (int i = 0, exp = 1; i < numberOfDigits(max); i++, exp *= BASE) {
countingSortByDigit(array, exp);
}
}
private static int numberOfDigits(int number) {
int digits = 0;
do {
digits++;
number /= 10;
} while (number != 0);
return digits;
}
radixSort finds the largest value and runs one pass for each of its digits. i counts the passes, and exp is the place value of the current digit: 1 for the ones, 10 for the tens, 100 for the hundreds. numberOfDigits divides by 10 until nothing is left. The do-while loop counts at least one digit, so an array of zeros still gets one pass.
Two details are worth noticing:
numberOfDigits(max)is in the loop condition, so it runs again before every pass. The result never changes; computing it once before the loop would do.numberOfDigitsdivides by the literal10, not byBASE, so the two only agree whileBASEis 10. WithBASE = 2, a value like 802 needs ten binary digits but gets only three passes, and the array comes back partly sorted. WithBASE = 256, the passes multiplyexpby 256 each time, and for values with more than four decimal digits it overflows to 0 on the fifth pass, sogetDigitthrows anArithmeticExceptionfor dividing by zero.
countingSortByDigit
1
2
3
4
5
6
private static void countingSortByDigit(int[] array, int exp) {
int[] count = countDigits(array, exp);
accumulateCounts(count);
int[] output = buildOutput(array, exp, count);
copyOutput(array, output);
}
countingSortByDigit is one pass: a counting sort that uses the digit at exp as the key. It counts the digits, turns the counts into running totals, builds the sorted output, and copies it back into array, ready for the next pass.
countDigits and getDigit
1
2
3
4
5
6
7
8
9
10
11
private static int[] countDigits(int[] array, int exp) {
int[] count = new int[BASE];
for (int i = 0; i < array.length; i++) {
count[getDigit(array[i], exp)]++;
}
return count;
}
private static int getDigit(int number, int position) {
return (number / position) % BASE;
}
countDigits creates a count array with one slot per digit and adds one to the slot of each value’s digit. getDigit extracts that digit: dividing by exp drops the digits to the right, and % BASE keeps only the last remaining one. For 802 and exp = 10, that is 80 % 10, which is 0.
accumulateCounts
1
2
3
4
5
private static void accumulateCounts(int[] count) {
for (int i = 1; i < BASE; i++) {
count[i] += count[i - 1];
}
}
accumulateCounts replaces each slot with the sum of itself and all slots before it. Afterwards, count[d] is the number of values whose digit is d or smaller: the position just past the last value with digit d in the output.
buildOutput
1
2
3
4
5
6
7
8
9
private static int[] buildOutput(int[] array, int exp, int[] count) {
int[] output = new int[array.length];
for (int i = array.length - 1; i >= 0; i--) {
int digit = getDigit(array[i], exp);
output[count[digit] - 1] = array[i];
count[digit]--;
}
return output;
}
buildOutput walks the array from the back and places each value at the last free position for its digit, then lowers that slot by one. Walking backwards is what makes the pass stable: the last value with a given digit lands at the end of its group, and each earlier one lands to its left. Without that, a later pass would scramble the order the earlier passes worked for.
copyOutput
1
2
3
private static void copyOutput(int[] array, int[] output) {
System.arraycopy(output, 0, array, 0, array.length);
}
copyOutput copies the pass’s result back into the original array with System.arraycopy, so the next pass starts from the new order. A new output array is created on every pass; allocating it once in radixSort and swapping the two arrays between passes would save the copies.
Running it
1
2
3
4
int[] numbers = {170, 45, 75, 90, 802, 24, 2, 66};
RadixSort.sort(numbers);
System.out.println(Arrays.toString(numbers));
// [2, 24, 45, 66, 75, 90, 170, 802]
Call the static sort method; numbers itself is sorted, and the same array is also returned. The largest value, 802, has three digits, so the sort makes three passes.
Summary
- Radix Sort is a non-comparison sort for integers: it sorts the values one digit at a time, from the ones digit up.
- This implementation is an LSD radix sort in base 10: each pass is a stable counting sort on one digit, written to an output array and copied back.
- After the pass for a digit, the array is sorted by that digit and all the digits to its right, so the last pass leaves the whole array sorted.
- It runs in $O(d(n + b))$ time and needs $O(n + b)$ extra space, is stable but not in place, and only accepts non-negative values.
- Use it for many integers or fixed-width keys. When there are only a few values, or the keys aren’t integers, a comparison sort such as
Arrays.sort()is simpler and often just as fast.
