Sleep Sort

Sort by timeouts.

Best O(max(n)) Avg O(max(n)) Worst O(max(n)) Space O(n) Stable No In-place No Comparison-based

How it works

Sort by timeouts.

Implementation

function sleepSort(arr, stats) {
  const n = arr.length;
  if (n < 2) return;
  let min = arr[0];
  for (let i = 1; i < n; i++) min = Math.min(min, arr[i]);
  const offset = min < 0 ? -min : 0;
  const awakened = [];
  const events = arr.map((value, idx) => ({
    wake: (value + offset) * 4 + idx * 1e-6,
    value
  }));
  for (let e = 0; e < events.length; e++) {
    const event = events[e];
    let i = awakened.length;
    while (i > 0) {
      if (awakened[i - 1].wake <= event.wake) break;
      i--;
    }
    awakened.splice(i, 0, event);
  }
  for (let i = 0; i < n; i++) {
    arr[i] = awakened[i].value;
    write(i, awakened[i].value);
    markSorted(i);
  }
}