Post

Counting Sort in Java

Learn how Counting 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.

Counting Sort in Java

Introduction

Counting Sort is a non-comparison sort for integers. It never compares two values with each other. Instead, it counts how often each value occurs, and uses those counts to work out where every value belongs in the sorted output.

Three ideas carry the whole algorithm:

  • Histogram: an array with one slot per possible value, holding how many times that value occurs.
  • Cumulative count: running totals over the histogram, so each slot holds how many values are less than or equal to its value. That is exactly the position just after the last copy of that value in the sorted output.
  • Shift: the smallest value is subtracted from every value before it is used as an index, so the count array starts at slot 0 and negative values work too.

Comparison sorts can’t beat $O(n \log n)$, but Counting Sort runs in linear time when the values fall in a small range, such as ages, exam marks or bytes. It is also stable, which makes it the building block of radix sort: radix sort runs a counting sort on each digit in turn, and that only works because each pass keeps the order of the one before.

This article uses a stable counting sort with a minimum shift: it builds the histogram, turns it into cumulative counts, and then walks the input backwards to place each value into a new output array.

Performance Characteristics

Counting Sort doesn’t depend on the order of the input at all, only on how many values there are and how far apart the smallest and largest value are.

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 and $k$ is the spread, the number of slots from the smallest to the largest value ($\max - \min + 1$).

CaseTimeWhen it happens
Best$O(n + k)$Any input: the same four passes run every time
Average$O(n + k)$Any input
Worst$O(n + k)$Any input, but slow when $k$ is much larger than $n$

Why $n + k$? Finding the minimum and maximum, building the histogram and placing the values each walk the input once ($n$ work each), and creating and summing the count array walks the $k$ slots once. No step depends on how the values are ordered.

Counting Sort only pays off when $k$ is not much larger than $n$. Sorting ten values between 0 and 1,000,000 creates a count array with a million slots, and summing them costs far more than a comparison sort would. For a wide range, use radix sort or Arrays.sort().

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(n + k)$: the count array has $k$ slots and the output has $n$ values
In placeNo (the sorted values are written to a new array)
StableYes (the input is placed from the back, into the back of each value’s run)

Algorithm (Pseudo Code)

Counting Sort starts by finding the smallest and largest value, and creates a count array with one slot for every value in between. One pass over the input adds one to the slot of each value, so afterwards each slot says how often its value occurs. Then the slots are added up from left to right: each slot gets the sum of itself and every slot before it. Now a slot says how many values are less than or equal to its value, which is the position just past the last copy of that value in the sorted output.

The last pass walks the input from the back to the front. For each value, it looks up its slot, places the value at the slot’s count minus one, and lowers the count by one, so the next copy of the same value lands just to its left. When the pass reaches the front, every value has been placed and the output is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sort(array):
    min = smallest value, max = largest value
    count = computeHistogram(array, min, max - min + 1)
    toCumulative(count)
    return reconstructSorted(count, min, array)

computeHistogram(array, shift, spread):
    res = new int[spread]
    for each value in array:
        res[value - shift]++

toCumulative(count):
    for i = 1 to length - 1:
        count[i] += count[i - 1]

reconstructSorted(count, shift, array):
    res = new int[array.length]
    for i = array.length - 1 down to 0:
        res[count[array[i] - shift] - 1] = array[i]
        count[array[i] - shift]--
    return res

After toCumulative, slot i holds the number of values that are less than or equal to i + min, so the copies of that value belong in the positions just before it.

Walking backwards is what makes the sort stable. The last copy of a value is placed first, at the end of that value’s run, and each earlier copy lands to its left, so equal values keep their original order. A forward walk would reverse them.

Visualization

The visualization below follows the Java code line by line, starting with ten values between 1 and 5.

Counting Sort is all about repeated values, so instead of the values 0 to 9, the visualization starts with [4, 2, 5, 4, 1, 3, 2, 4, 5, 2]. The smallest value is 1, so the shift is visible: the value v is counted in slot v - 1.

Each step shows the input, 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. The range moves around, and sometimes includes negative values.
  • Rows: the top row is the input array, the middle row the count array, with the value each slot counts below it, and the bottom row the output res.
  • Pointer: I is i in reconstructSorted, walking the input from the back.
  • Original index: the small number in the corner of each value is its index in the input. In the output, equal values keep these in increasing order, which shows that the sort is stable.
  • Colours: the value being read is amber, the cell being written is salmon, and values placed in the output are green.
read written placed in output I = i

Java Code

The implementation is a CountingSort utility class: it is final, has a private constructor, and offers one public static method, sort, for int arrays. Three private methods do the work: computeHistogram counts the values, toCumulative turns the counts into running totals, and reconstructSorted builds the sorted output. The class doesn’t use the SortUtils helpers, because it never compares or swaps.

The complete code is in the algorithm-examples repository on GitHub: CountingSort.java.

sort

1
2
3
4
5
6
7
8
9
10
public static int[] sort(int[] array) {
    if (array.length == 0) {
        return array;
    }
    final var stats = Arrays.stream(array).summaryStatistics();
    final int min = stats.getMin();
    int[] count = computeHistogram(array, min, stats.getMax() - min + 1);
    toCumulative(count);
    return reconstructSorted(count, min, array);
}

sort is the entry point. An empty array comes straight back. Otherwise summaryStatistics() finds the smallest and largest value in one pass, and the spread max - min + 1 sets the size of the count array. The three steps then run in order, and sort returns the new array that reconstructSorted builds. The input array itself is not changed.

Two details are worth noticing:

  • Unlike the other sorts in this guide, CountingSort doesn’t implement SortAlgorithm and only works on int[], not on any Comparable type, because it uses the values themselves as array indices.
  • The caller must use the return value: CountingSort.sort(numbers) on its own leaves numbers unsorted.

stats.getMax() - min + 1 is computed in int and can overflow when the values are far apart. For {-2_000_000_000, 2_000_000_000}, the spread wraps around to a negative number and new int[spread] throws a NegativeArraySizeException. For {Integer.MIN_VALUE, Integer.MAX_VALUE}, it wraps to 0 and the histogram throws an ArrayIndexOutOfBoundsException. Even without overflow, a spread of a billion asks for a 4 GB count array. Checking the spread as a long first, and falling back to another sort when it is too large, avoids all three.

computeHistogram

1
2
3
4
5
6
7
private static int[] computeHistogram(final int[] array, final int shift, final int spread) {
    int[] res = new int[spread];
    for (final var value : array) {
        res[value - shift]++;
    }
    return res;
}

computeHistogram creates the count array with one slot per value in the range, all starting at zero, and adds one to the slot of every value. Subtracting shift, the minimum, maps the smallest value to slot 0 and the largest to slot spread - 1, which is why negative values work.

toCumulative

1
2
3
4
5
private static void toCumulative(int[] count) {
    for (int i = 1; i < count.length; i++) {
        count[i] += count[i - 1];
    }
}

toCumulative replaces each slot with the sum of itself and all slots before it, in place. Afterwards, count[i] is the number of values that are less than or equal to i + min. For the visualization’s data, the histogram [1, 3, 1, 3, 2] becomes [1, 4, 5, 8, 10]: one value is ≤ 1, four values are ≤ 2, and so on, until the last slot holds the length of the array.

reconstructSorted

1
2
3
4
5
6
7
8
private static int[] reconstructSorted(final int[] cumulativeCount, final int shift, final int[] array) {
    int[] res = new int[array.length];
    for (int i = array.length - 1; i >= 0; i--) {
        res[cumulativeCount[array[i] - shift] - 1] = array[i];
        cumulativeCount[array[i] - shift]--;
    }
    return res;
}

reconstructSorted creates the output array and walks the input from the last index to the first. Each value’s slot says how many values are ≤ it, so the value goes to position slot - 1, the last free position for that value. The slot is then lowered by one, so the next copy of the same value, further to the left in the input, lands one position further left in the output.

For int values, stability can’t be seen in the result, because equal integers are identical. It matters as soon as the values carry more data, such as records sorted by a key, or the digits of a number in radix sort.

Running it

1
2
3
4
int[] numbers = {4, -2, 5, 4, 1, 3, -2, 0};
int[] sorted = CountingSort.sort(numbers);
System.out.println(Arrays.toString(sorted));
// [-2, -2, 0, 1, 3, 4, 4, 5]

Call the static sort method and keep the array it returns; numbers is left as it was. The smallest value is -2, so the count array has 8 slots, for the values -2 to 5.

Summary

  • Counting Sort is a non-comparison sort for integers: it counts how often each value occurs and computes every value’s position from those counts.
  • This implementation shifts the values by the minimum, builds a histogram, turns it into cumulative counts, and places the values into a new array, walking the input backwards.
  • After toCumulative, each slot holds how many values are less than or equal to its value, which is where the last copy of that value belongs.
  • It runs in $O(n + k)$ time and needs $O(n + k)$ extra space, where $k$ is the spread of the values. It is stable but not in place.
  • Use it when the values are integers in a small range. When the range is wide, choose radix sort, which applies counting sort one digit at a time, or a comparison sort such as Arrays.sort().
This post is licensed under CC BY 4.0 by the author.