Every sort so far asks the same question over and over: of these two numbers, which is bigger? Can you sort without comparing at all? You can, as long as the numbers are whole and not negative, with a small range of values (from the smallest value to the largest).
Counting sort counts how many times each value appears, then builds the result from those counts. It's like counting votes with tally marks, one small line for each vote. Each choice has its own column, and the final result is read from the first column to the last. In counting sort, each number value is one choice, and its column is one box in a helper array, count.
Count, accumulate, place
The count array has a box for each value, from 0 up to the largest number. The box at index 4 holds the count of the number 4, and so on. Here's what happens to [4, 2, 2, 8, 3, 3, 1], in three phases:
| Phase | What it does | Result |
|---|---|---|
| 1. Count | each number adds one to its own box: the number 4 adds to count[4] |
count = [0, 1, 2, 2, 1, 0, 0, 0, 1] |
| 2. Accumulate | each box adds the box before it | count = [0, 1, 3, 5, 6, 6, 6, 6, 7] |
| 3. Place | read the input from the right: 1 to index 0, 3 to index 4, 3 to index 3, and so on | [1, 2, 2, 3, 3, 4, 8] |
Here is the code:
function countingSort(arr) {
const max = Math.max(...arr);
const count = new Array(max + 1).fill(0); // max + 1 boxes
// 1. Count: count[v] = how many times v appears
for (const v of arr) count[v]++;
// 2. Accumulate: count[v] = how many numbers are <= v
for (let v = 1; v <= max; v++) count[v] += count[v - 1];
// 3. Build the output, from the right so it's stable
const output = new Array(arr.length);
for (let i = arr.length - 1; i >= 0; i--) {
count[arr[i]]--;
output[count[arr[i]]] = arr[i];
}
return output;
}
console.log(countingSort([4, 2, 2, 8, 3, 3, 1]));
// [1, 2, 2, 3, 3, 4, 8]
Math.max(...arr)finds the largest number, 8.new Array(max + 1).fill(0)makes 9 boxes holding 0, index 0 to 8. Only 7 numbers, but 9 boxes: the number of boxes follows the largest value, not the number of items.for (const v of arr)takes each number inarr, one at a time, asv. Thencount[v]++adds one to box numberv: the number itself is the index of its box. No two numbers are ever compared.- Accumulating means each box adds the value of the box before it. After accumulating,
count[3]= 5: 5 numbers are less than or equal to 3. Those 5 numbers fill indexes 0 to 4, so the last 3 sits at index 4. - Phase 3 reads the numbers from the right. For each number, its box goes down by one, then the number goes to the index equal to the box's new value. For example, for the last 3,
count[3]goes down from 5 to 4. Because phase 3 goes from the right, equal numbers keep their original order. A sort that keeps the original order of equal values is called stable. That matters when you sort records, for example students by their score.
If you are sorting only numbers, there's a shortcut: after phase 1, write each value out as many times as its count. From count[1] = 1, count[2] = 2, count[3] = 2, count[4] = 1 and count[8] = 1, you get [1, 2, 2, 3, 3, 4, 8] right away.
When counting sort wins
In Big-O, counting sort is O(n + k): n is the number of items, and k is the number of boxes (the range of values). Phases 1 and 3 go through the n numbers, and phase 2 goes through the k boxes. Sorts that compare, like merge sort and quick sort, need about O(n log n).
- k small next to n: it wins. Exam scores from 0 to 100 for 1,000 students: about 1,000 + 101 steps, while n log n is about 10,000.
- k large: wasteful.
[5, 1000000]is only 2 numbers, but needs about a million boxes. - Not whole numbers: no direct way. Decimals and text can't be a box's index. Negative numbers can't either, even though they are whole.
⚠️ One box short, negative numbers, and swapped duplicates
- One box short.
new Array(max)only has indexes 0 tomax - 1, so the largest number has no box. It has to bemax + 1. - Negative numbers.
count[-1]doesn't exist. Shift all the numbers first: subtract the smallest number from each one, so the smallest becomes 0. When placing, add the smallest number back. - Phase 3 from the left. The result is still sorted, but equal numbers swap their order, so the sort is no longer stable.
- A very large array, or an empty one.
Math.max(...arr)sends each number toMath.maxas a separate argument (a value passed to a function), and the space for arguments is limited. In Node 24, 125,000 numbers are enough to make that line stop withRangeError: Maximum call stack size exceeded, although counting sort is meant for large data. An empty array fails too.Math.max()with no numbers gives-Infinity(minus infinity), and an array's length can't be negative, sonew Array(-Infinity + 1)stops withRangeError: Invalid array length.
For real data, replace the line const max = Math.max(...arr); with these three lines. If arr is empty, the function returns [] right away. If not, a loop finds the largest number:
if (arr.length === 0) return [];
let max = arr[0];
for (const v of arr) if (v > max) max = v;
With those three lines, 1,000,000 numbers from 0 to 100 are sorted with no error.
TL;DR: Counting sort sorts without comparing numbers. Phase 1 counts how many times each value appears and records it in a count array: one box per value, from 0 to the largest number (max), so max + 1 boxes. Phase 2 accumulates the counts (each box adds the box before it). Phase 3 puts each number in its place, from the right so it's stable: equal numbers keep their original order. If you sort only numbers, with no other data, just write each value as many times as its count. It takes O(n + k) time, where n is the number of items and k the number of boxes (the range of values). So counting sort wins when k is small compared with n, like exam scores from 0 to 100 for 1,000 students. It only works for whole numbers. If there are negative numbers, shift all the numbers first: subtract the smallest number from each one, so the smallest becomes 0, and add it back when placing.
⚡ Sorting without comparing
Write:
function countingSort(arr) {
const max = Math.max(...arr);
const count = new Array(max + 1).fill(0); // max + 1 boxes
// 1. Count: count[v] = how many times v appears
for (const v of arr) count[v]++;
// 2. Accumulate: count[v] = how many numbers are <= v
for (let v = 1; v <= max; v++) count[v] += count[v - 1];
// 3. Build the output, from the right so it's stable
const output = new Array(arr.length);
for (let i = arr.length - 1; i >= 0; i--) {
count[arr[i]]--;
output[count[arr[i]]] = arr[i];
}
return output;
}
Meaning: Counting sort counts how many times each value appears. The count array has a box for each value, from 0 to the largest number, so there are max + 1 boxes. The number itself is the index of its box (count[v]++), so no two numbers are ever compared.
⚡ From the right, so it's stable
Meaning: For [4, 2, 2, 8, 3, 3, 1], after accumulating (each box adds the box before it), count[3] = 5. That means 5 numbers are less than or equal to 3. Those 5 numbers fill indexes 0 to 4, so the last 3 sits at index 4. Phase 3 reads the input from the right, so equal numbers keep their original order. A sort that keeps that order is called stable.
⚡ When counting sort wins
Guess first: [5, 1000000] is only 2 numbers. How many boxes does counting sort need?
1,000,001 boxes (max + 1), about a million. The number of boxes follows the largest value, so a wide range of values is wasteful.
Meaning: It takes O(n + k), where n is the number of items and k is the number of boxes. Counting sort wins when k is small compared with n, like exam scores from 0 to 100 for 1,000 students. It only works for whole numbers. If there are negative numbers, shift all the numbers first: subtract the smallest number from each one, so the smallest becomes 0, and add it back when placing.