Counting Sort: Keys, Counts and Cost
Count how many times each key appears, turn those counts into output positions, then place every value straight into its slot. No two values are ever compared.
How Counting Sort Works
- Find the smallest and largest value; k = high − low + 1
- Count: for each value v, add 1 to count[v − low]
- Prefix sums: count[i] += count[i − 1], so each slot holds one past its key's last position
- Place: walk the input from the end; decrease count[v − low] and write v at that position
Counting sort sorts integers in a known, limited range without comparing them. Instead of asking which of two values is smaller, it uses each value as an index into a count array. That is why it can beat the n log n limit, which only binds sorts that learn the order through comparisons.
The counting sort algorithm has four passes. On [2, 5, 3, 2, 5, 2] the keys run from 2 to 5, so k = 4. The counts are 3, 1, 0, 2; their running totals are 3, 4, 4, 6, which say the 2s end before position 3, the 3 before 4 and the 5s before 6.
- The value is the index: no comparisons at all
- Subtracting low lets the keys start anywhere, including below 0
Is Counting Sort Stable?
Yes, in its standard form. Stable means equal keys come out in the order they went in. Each key's counter starts one past its last position and is decreased before every write, so each key's positions are handed out from the back. Reading the input from the back too means the last of the equal values takes the last place, the one before it takes the place before, and the original order survives.
Run the placement loop forwards instead and the output is still sorted, but equal keys come out reversed. With plain numbers you cannot see the difference, so tests pass. With records sorted by a key, such as students by grade, the earlier order is lost.
Stability is why counting sort is the inner step of radix sort. Radix sort sorts by the last digit, then the next, and so on; each pass must keep the order the earlier passes made, or the result is wrong.
- Backward placement: stable
- Forward placement with the same counters: sorted but equal keys reversed
Counting Sort Time Complexity
Counting and placing each touch every value once, O(n). The prefix pass touches every key once, O(k). There is no best or worst case, because nothing depends on the order of the input.
- Time: O(n + k) in every case, where k is the key range
- Space: O(n + k) for the count array and the output array
- Linear when k is O(n)
- Not in place: it writes to a separate output array
Terms, operations, and practical uses
The passes
- CountOne pass over the input, adding 1 to count[v − low] for each value v.
- Prefix sumsRunning totals of the counts. Slot i then holds how many values are less than or equal to key low + i.
- PlaceFrom the last value to the first: decrease the key's counter, then write the value at that index.
Cost
- nThe number of values. Counting and placing are O(n).
- kThe number of possible keys, high − low + 1. The count array and the prefix pass are O(k).
- Non-comparison sortIt never compares two values, so the n log n lower bound for comparison sorts does not apply.
Behaviour
- StableEqual keys keep their input order, because placement runs backwards.
- Not in placeNeeds an output array of size n as well as the count array.
- Integer keysKeys must be integers in a known range, or map onto them.
Code in Python, C++ and Java
def counting_sort(values):
if not values:
return values
low, high = min(values), max(values)
counts = [0] * (high - low + 1)
for value in values:
counts[value - low] += 1
for key in range(1, len(counts)):
counts[key] += counts[key - 1]
output = [0] * len(values)
for value in reversed(values): # backwards keeps equal keys in order
counts[value - low] -= 1
output[counts[value - low]] = value
return output
for data in [[2, 5, 3, 2, 5, 2], [3, -1, 0, -1, 2]]:
print(" ".join(map(str, data)), "->", " ".join(map(str, counting_sort(data))))#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<int> countingSort(const vector<int>& values) {
if (values.empty()) return values;
int low = *min_element(values.begin(), values.end());
int high = *max_element(values.begin(), values.end());
vector<int> counts(high - low + 1, 0);
for (int value : values) counts[value - low]++;
for (size_t key = 1; key < counts.size(); key++) counts[key] += counts[key - 1];
vector<int> output(values.size());
for (int i = (int)values.size() - 1; i >= 0; i--) { // backwards keeps equal keys in order
counts[values[i] - low]--;
output[counts[values[i] - low]] = values[i];
}
return output;
}
void print(const vector<int>& v) {
for (size_t i = 0; i < v.size(); i++) cout << (i ? " " : "") << v[i];
}
int main() {
vector<vector<int>> inputs = {{2, 5, 3, 2, 5, 2}, {3, -1, 0, -1, 2}};
for (const vector<int>& data : inputs) {
print(data);
cout << " -> ";
print(countingSort(data));
cout << "\n";
}
}import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
static int[] countingSort(int[] values) {
if (values.length == 0) return values;
int low = Arrays.stream(values).min().getAsInt();
int high = Arrays.stream(values).max().getAsInt();
int[] counts = new int[high - low + 1];
for (int value : values) counts[value - low]++;
for (int key = 1; key < counts.length; key++) counts[key] += counts[key - 1];
int[] output = new int[values.length];
for (int i = values.length - 1; i >= 0; i--) { // backwards keeps equal keys in order
counts[values[i] - low]--;
output[counts[values[i] - low]] = values[i];
}
return output;
}
static String show(int[] v) {
return Arrays.stream(v).mapToObj(String::valueOf).collect(Collectors.joining(" "));
}
public static void main(String[] args) {
int[][] inputs = {{2, 5, 3, 2, 5, 2}, {3, -1, 0, -1, 2}};
for (int[] data : inputs) System.out.println(show(data) + " -> " + show(countingSort(data)));
}
}Step through it
Running on [2, 5, 3, 2, 5, 2], equal keys tagged a, b, c; then [3, 1000000, 7]
When the Key Range Is Too Wide
The k term decides whether counting sort is a good idea. A million exam scores from 0 to 100 need 101 counters, and no comparison sort comes close. Three values such as 3, 1,000,000 and 7 need almost a million counters, nearly all zero. Sorting arbitrary 32-bit integers could need over four billion.
Rule of thumb: use counting sort when k is not much bigger than n. Wide integer ranges are better served by radix sort, which runs counting sort on one digit at a time so each pass has k = 10 or 256. Values with no integer key, such as real numbers spread over a range, suit bucket sort.
| Input | n | k | Counting sort? |
|---|---|---|---|
| Exam scores 0 to 100 | 1,000,000 | 101 | Ideal |
| Ages 0 to 120 | 50,000 | 121 | Ideal |
| Any 32-bit integers | 1,000,000 | about 4.3 billion | No: use radix sort |
- Small k: linear and very fast
- Huge k: the count array costs more than the sort
Edge Cases and a Shorter Version
For plain integers with no attached data, the prefix and placement passes can be skipped: after counting, write each key out as many times as it was counted. That is simpler, but it only works when equal values are truly identical. To sort records by an integer key, use the full four-pass version.
- Empty input: return it at once; there is no min or max to read
- Negative values: index with v − low, so −3 to 3 uses slots 0 to 6
- One distinct value: k = 1 and the output equals the input
- Large counts: use a type wide enough for n, since a count can reach n