Counting Sort

Sort whole numbers by counting how often each value appears, then placing every value straight into its sorted position.

Given an array of integers arr, return a new array with the same values in ascending order. Do it by counting the values, without comparing two values with each other.

Example
Input: arr = [4, 2, 2, 8, 3, 3, 1]
Output: [1, 2, 2, 3, 3, 4, 8]
Solution

The Idea

Imagine seven cards on a table, showing 4, 2, 2, 8, 3, 3 and 1, and you know every card shows a number from 1 to 8. You could compare cards two at a time and swap them around. There is another way, with no comparisons at all: set out eight boxes, labelled 1 to 8, and drop each card into the box with its number.

Then count the cards in each box: one 1, two 2s, two 3s, one 4, nothing in boxes 5, 6 and 7, and one 8. Writing each number as often as it was counted gives 1, 2, 2, 3, 3, 4, 8. No card was ever compared with another card.

For bare numbers, that is enough. Often, though, each number is the key of something larger, the part it is sorted by, such as the length of a word, and two words can share a length. Writing out the length twice would lose the words. So the real question is: at which position of the output does each card belong?

The counts answer that too, once they are added up from the left. The 1s fill 1 place, the 1s and 2s together fill 3 places, and everything up to 3 fills 5 places. So the 3s end just before output index 5, at indexes 3 and 4. Each added-up count is called a running total.

Counting sort on 4, 2, 2, 8, 3, 3, 1. The row count of each value holds 1, 2, 2, 1, 0, 0, 0, 1 for the values 1 to 8. The row running total holds 1, 3, 5, 6, 6, 6, 6, 7. The running total for 3 is 5, so the two 3s fill output indexes 4 and 3, and the output is 1, 2, 2, 3, 3, 4, 8.

The top row of the picture, labelled input, is the array, with the two 3s in orange at indexes 4 and 5. The row labelled count of each value has one box per value from 1 to 8. The row labelled running total adds those counts up, so its orange 5 says that five values are 3 or less.

Now walk the input from its last index back to the first. The 3 at input index 5 takes the last of the 3s' places, output index 4. The 3 at input index 4 takes output index 3. The bottom row, labelled output, is the sorted array.

Sorting by counting values instead of comparing them is called counting sort. It is the building block of radix sort.

Solution Approach

Four decisions shape the code: how many boxes the count array needs, where negative numbers go in it, which way to walk the input when placing values, and what to do when the values are spread too far apart.

Size of the count array

How many boxes are needed? One for every value from the smallest, min, to the largest, max. That makes max - min + 1 boxes; call this number k. For the cards, k is 8 - 1 + 1 = 8. One pass over the input finds min and max.

Negative numbers

What about a value like -5? An array has no index -5. Subtracting min from every value fixes that: value v is counted in box v - min. For [-5, 3, 0, -5, 2], min is -5, so -5 is counted in box 0 and 3 in box 8.

Placing from the end

Why walk the input backwards? The running total for a value is one past the last place that value may take. Each time a value is placed, its running total first drops by one, so the next copy of that value lands one place to the left.

Walking from the end, the last 3 in the input takes the last place for 3s, and the earlier 3 takes the place before it. Equal values therefore come out in the same order as they went in. A sort that keeps equal values in their input order is called stable. Radix sort depends on that, because it sorts the same numbers again and again, one digit at a time.

Values spread too far apart

What if the input is just two numbers, Integer.MIN_VALUE and Integer.MAX_VALUE? Then k is 4,294,967,296, more boxes than a Java array can have. Worse, max - min + 1 computed as int passes the largest int and wraps around to 0.

The code therefore computes k as a long and refuses a range above a limit, MAX_RANGE, set here to 224 boxes (16,777,216 boxes, 64 MB of int counts). Pick a limit that fits your memory. Above it, a comparison sort such as Arrays.sort is the better tool.

Java Solution

The method sort works in these steps:

  1. First, if arr is empty, return it, since there is nothing to count.
  2. Find the smallest value, min, and the largest, max, with one loop over arr.
  3. Compute k as a long in a variable named range. If range is above MAX_RANGE, throw an IllegalArgumentException that names the range.
  4. Create the array count with range boxes. A second loop goes over arr and adds 1 to count[v - min] for each value v.
  5. A third loop turns the counts into running totals by adding each box's left neighbour to it: count[i] += count[i - 1].
  6. Create the array output, the same length as arr. A fourth loop walks arr from the last index down to 0. For each value it lowers that value's running total by one and writes the value at that index of output.
  7. Finally, return output.

A second method, sortByLength, runs the same counting, running-total and placing loops on words, with each word's length as its key, so the order of equal keys shows in the output.

The main method sorts the example, an array with negative numbers, three equal values and an empty array, then five words by length, and finally the two most distant int values.

Java
import java.util.Arrays;

public class CountingSort {

    static final int MAX_RANGE = 1 << 24;   // at most 16,777,216 counts (64 MB of ints)

    public static int[] sort(int[] arr) {
        if (arr.length == 0) {
            return arr;
        }
        int min = arr[0];
        int max = arr[0];
        for (int v : arr) {
            min = Math.min(min, v);
            max = Math.max(max, v);
        }
        long range = (long) max - min + 1;          // long: max - min can pass the int limit
        if (range > MAX_RANGE) {
            throw new IllegalArgumentException("value range too large: " + range);
        }

        int[] count = new int[(int) range];
        for (int v : arr) {
            count[v - min]++;                       // slot 0 is min, slot 1 is min + 1, ...
        }
        for (int i = 1; i < count.length; i++) {
            count[i] += count[i - 1];               // now: how many values are <= i + min
        }
        int[] output = new int[arr.length];
        for (int i = arr.length - 1; i >= 0; i--) { // from the end, so equal values keep order
            output[--count[arr[i] - min]] = arr[i];
        }
        return output;
    }

    // The same three steps, sorting words by their length, to show the order of equal keys.
    public static String[] sortByLength(String[] words) {
        int maxLen = 0;
        for (String w : words) {
            maxLen = Math.max(maxLen, w.length());
        }
        int[] count = new int[maxLen + 1];
        for (String w : words) {
            count[w.length()]++;
        }
        for (int i = 1; i < count.length; i++) {
            count[i] += count[i - 1];
        }
        String[] output = new String[words.length];
        for (int i = words.length - 1; i >= 0; i--) {
            output[--count[words[i].length()]] = words[i];
        }
        return output;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(sort(new int[] {4, 2, 2, 8, 3, 3, 1})));
        System.out.println(Arrays.toString(sort(new int[] {-5, 3, 0, -5, 2})));
        System.out.println(Arrays.toString(sort(new int[] {7, 7, 7})));
        System.out.println(Arrays.toString(sort(new int[] {})));
        String[] words = {"kiwi", "fig", "pear", "plum", "yam"};
        System.out.println(Arrays.toString(sortByLength(words)));
        try {
            sort(new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE});
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Running it prints:

Output
[1, 2, 2, 3, 3, 4, 8]
[-5, -5, 0, 2, 3]
[7, 7, 7]
[]
[fig, yam, kiwi, pear, plum]
value range too large: 4294967296

The example comes out as [1, 2, 2, 3, 3, 4, 8], matching the bottom row of the picture. In the second line, both copies of -5 were counted in box 0 and lead the output. Three 7s give a count array of one box, and the empty array comes straight back as [].

Now look at the words. The input was [kiwi, fig, pear, plum, yam]. In the output, fig still comes before yam, and kiwi, pear and plum keep their input order too: the sort is stable. Changing the placing loop to run from the front gives [yam, fig, plum, pear, kiwi] instead. The words are still sorted by length, but each group of equal lengths is reversed.

The last line is the range guard at work: k is 4,294,967,296. Without the long and the limit, the same input fails in a confusing way. The int range wraps to 0, and the counting loop throws ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0.

Complexity

Counting sort makes three passes over the n input values and one pass over the k boxes, whatever order the values arrive in.

  • Time, best case: O(n), when k is no larger than n, as in [1, 0, 3, 1, 3, 1], where six values share four boxes.
  • Time, average case: O(n + k), because the loops do the same steps for any order of the same values: a shuffled array and an already sorted one cost the same.
  • Time, worst case: O(n + k) with k far above n, as in [0, 16000000], where two values make the running-total loop walk through 16,000,001 boxes.
  • Space: O(n + k), because output holds a copy of all n values and count holds k boxes, on top of the input array, which is never rearranged.

Sorts that compare two values at a time need on the order of n log n comparisons in the worst case. Counting sort escapes that bound only while k stays small. Radix sort keeps k small for large numbers by running a stable counting pass once per digit, with ten boxes for the digits 0 to 9.