Stalin Sort

Eliminates out of order elements.

Best O(n) Avg O(n) Worst O(n) Space O(1) Stable Yes In-place Yes Comparison-based

How it works

Eliminates out of order elements.

Implementation

function stalinSort(arr, stats) {
  const n = arr.length;
  if (n < 2) return;
  const kept = [];
  const purged = [];
  for (let i = 0; i < n; i++) {
    const v = arr[i];
    if (kept.length === 0) {
      kept.push(v);
    } else {
      compare(i - 1, i);
      if (v >= kept[kept.length - 1]) kept.push(v); else purged.push(v);
    }
  }
  for (let i = 1; i < purged.length; i++) {
    const key = purged[i];
    let j = i - 1;
    while (j >= 0) {
      if (purged[j] <= key) break;
      purged[j + 1] = purged[j];
      j--;
    }
    purged[j + 1] = key;
  }
  const merged = [];
  let a = 0, b = 0;
  while (a < kept.length && b < purged.length) {
    if (kept[a] <= purged[b]) merged.push(kept[a++]); else merged.push(purged[b++]);
  }
  while (a < kept.length) merged.push(kept[a++]);
  while (b < purged.length) merged.push(purged[b++]);
  for (let i = 0; i < n; i++) {
    arr[i] = merged[i];
    write(i, merged[i]);
    markSorted(i);
  }
}