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 < 1) return;
  let max = arr[0];
  for (let i = 1; i < n; i++) max = Math.max(max, arr[i]);
  const count = new Array(max + 1).fill(0);
  for (let i = 0; i < n; i++) {
    count[arr[i]]++;
    compare(i, i);
  }
  let idx = 0;
  const sorted = new Set();
  for (let v = 0; v <= max; v++) {
    for (let c = 0; c < count[v]; c++) {
      arr[idx] = v;
      write(idx, v);
      markSorted(idx);
      idx++;
      checkpoint(idx, n);
    }
  }
}