Pigeonhole Sort

Distribution sort suitable when number of elements and range of possible values are roughly the same.

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

How it works

Distribution sort suitable when number of elements and range of possible values are roughly the same.

Implementation

function pigeonholeSort(arr, stats) {
  const n = arr.length;
  if (n < 1) return;
  let min = arr[0], max = arr[0];
  for (let i = 1; i < n; i++) {
    stats.comparisons += 2;
    if (arr[i] < min) min = arr[i];
    if (arr[i] > max) max = arr[i];
  }
  let range = max - min + 1;
  let holes = new Array(range).fill(0);
  for (let i = 0; i < n; i++) {
    holes[arr[i] - min]++;
  }
  let index = 0;
  for (let j = 0; j < range; j++) {
    while (holes[j] > 0) {
      holes[j]--;
      arr[index] = j + min;
      write(index, j + min);
      markSorted(index);
      index++;
    }
  }
}