Counting Sort

Counts occurrences of each value and uses arithmetic to place elements. Very fast when the range k is not much larger than n.

Best O(n+k) Avg O(n+k) Worst O(n+k) Space O(k) Stable Yes In-place No Distribution

How it works

Counts occurrences of each value and uses arithmetic to place elements. Very fast when the range k is not much larger than n.

Implementation

function countingSort(arr) {
  const max = Math.max(...arr);
  const count = new Array(max + 1).fill(0);
  for (let i = 0; i < arr.length; i++) count[arr[i]]++;
  let idx = 0;
  for (let v = 0; v <= max; v++)
    while (count[v]-- > 0) arr[idx++] = v;
}