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
Example
Output: [1, 2, 2, 3, 3, 4, 8]
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.
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
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, minmaxmax - min + 1minmax
Negative numbers
What about a value like -5? An array has no index -5. Subtracting minvv - min[-5, 3, 0, -5, 2]min
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_VALUEInteger.MAX_VALUEmax - min + 1intint
The code therefore computes k as a longMAX_RANGEintArrays.sort
Java Solution
The method sort
- First, if
is empty, return it, since there is nothing to count.arr - Find the smallest value,
, and the largest,min , with one loop overmax .arr - Compute k as a
in a variable namedlong . Ifrange is aboverange , throw anMAX_RANGE that names the range.IllegalArgumentException - Create the array
withcount boxes. A second loop goes overrange and adds 1 toarr for each valuecount[v - min] .v - A third loop turns the counts into running totals by adding each box's left neighbour to it:
.count[i] += count[i - 1] - Create the array
, the same length asoutput . A fourth loop walksarr 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 ofarr .output - Finally, return
.output
A second method, sortByLength
The mainint
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:
[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][]
Now look at the words. The input was [kiwi, fig, pear, plum, yam]figyamkiwipearplum[yam, fig, plum, pear, kiwi]
The last line is the range guard at work: k is 4,294,967,296. Without the longintArrayIndexOutOfBoundsException: 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
, where six values share four boxes.[1, 0, 3, 1, 3, 1] - 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
, where two values make the running-total loop walk through 16,000,001 boxes.[0, 16000000] - Space: O(n + k), because
holds a copy of all n values andoutput holds k boxes, on top of the input array, which is never rearranged.count
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.