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, stats) {
  const n = arr.length;
  if (n < 2) return;
  let max = arr[0];
  for (let i = 1; i < n; i++) {
    if (arr[i] > max) max = arr[i];
  }
  const count = new Array(max + 1).fill(0);
  for (let i = 0; i < n; i++) {
    count[arr[i]]++;
  }
  let idx = 0;
  for (let v = 0; v <= max; v++) {
    while (count[v] > 0) {
      arr[idx] = v;
      idx++;
      count[v]--;
    }
  }
}