Radix Sort

Sort non-negative integers one decimal digit at a time, starting with the ones digit.

Given an array arr of non-negative integers, sort it in ascending order. Do it with radix sort, which never compares two numbers with each other: it sorts them by one decimal digit at a time.

Example
Input: arr = [170, 45, 75, 90, 802, 24, 2, 66]
Output: [2, 24, 45, 66, 75, 90, 170, 802]
Solution

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.

Radix sort on 170, 45, 75, 90, 802, 24, 2, 66, each written with three digits. By ones digit: 170, 90, 802, 2, 24, 45, 75, 66. By tens digit: 802, 2, 24, 45, 66, 170, 75, 90, with 170 still ahead of 75. By hundreds digit: 2, 24, 45, 66, 75, 90, 170, 802.

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 exp that is 1 for the ones digit, 10 for the tens and 100 for the hundreds. It runs while max / exp is above 0. For 802, 802 / 1000 is 0, so the loop stops after exp = 100.

Why is exp a long? For a ten-digit maximum, such as 2,147,483,647 (the largest int), exp must reach ten billion before max / exp is 0. Ten billion does not fit in an int, which has 32 bits. In a run with an int multiplier, it wrapped around to 1,410,065,408 and then 1,215,752,192, giving two extra passes by positions that are not digits at all. The result still came out sorted, but those two passes were wasted work.

Reading one digit

How do we get the tens digit of 802 without turning it into text? Dividing by exp drops the digits to the right, and % 10 keeps the last digit of what is left. For the tens digit, exp is 10: 802 / 10 is 80, and 80 % 10 is 0. So the digit is (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 counting sort, used here on one digit at a time.

Java Solution

The method sort works in these steps:

  1. First, if arr is empty, return, because there is no largest value to find.
  2. Find the largest value, max, with Arrays.stream(arr).max().
  3. Loop with the long multiplier exp from 1, multiplying it by 10 each time, while max / exp is above 0. Each turn calls the helper method sortByDigit(arr, exp), which does one stable pass by the digit exp picks, in the next three steps.
  4. Inside sortByDigit, a loop over arr fills an array count of 10 entries: count[d] becomes how many numbers have digit d.
  5. A second loop adds to each entry the one before it, turning the counts into running totals. Now each entry of count is the position just after the last number with that digit.
  6. A third loop walks arr 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, output. Finally System.arraycopy copies output back into arr.

The main method first runs the example's three passes one by one, printing the array after each. Then it sorts the example, an empty array, one number, an array with repeats, an array of zeros, and an array holding Integer.MAX_VALUE.

Java
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:

Output
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 on the example, gives the same result as the hundreds pass.

The array of zeros prints [0, 0, 0] with no pass at all, because max / 1 is already 0. The last line puts 2147483647 after 1000000000, so all ten digits were sorted. A separate run that counted passes confirmed ten passes for that array.

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]. Each pass then reverses numbers that share a digit. After the tens pass of that run, 75 sat ahead of 170, the very tie the picture keeps in order, and the last pass reversed the whole hundreds-digit-0 tray.

The method also needs non-negative input, as the problem says. In Java, -1 / 1 % 10 is -1, and a run with [3, -1, 2] stopped with an ArrayIndexOutOfBoundsException on count[-1].

So the sort is stable, as each pass must be. It is not in place: every pass builds the extra array output, as long as the input.

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 [9, 3, 7, 1, 5], a single pass sorts the array, which a counting run confirmed.
  • Worst time: O(n) with ten passes, because one ten-digit value such as Integer.MAX_VALUE forces ten passes over all n numbers, and no int has more digits.
  • 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 output of n numbers and the array count of 10 entries.

Radix sort needs integer keys that split into digits. For negative numbers or values without digits, a comparison sort such as merge sort works on anything that can be compared, in O(n log n).