Counting Sort — Algorithms

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…

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]

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).

⚠️ One box short, negative numbers, and swapped duplicates

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.

What you will learn