Replacement Selection Sort

Heap-driven run generation technique commonly paired with external merge pipelines.

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

How it works

Heap-driven run generation technique commonly paired with external merge pipelines.

Implementation

function replacementSelectionSort(arr, stats) {
  const n = arr.length;
  if (n < 2) return;
  const heap = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    heap[i] = arr[i];
  }
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
    let root = i;
    while (true) {
      let smallest = root;
      const l = 2 * root + 1;
      const r = 2 * root + 2;
      if (l < n && heap[l] < heap[smallest]) smallest = l;
      if (r < n && heap[r] < heap[smallest]) smallest = r;
      if (smallest === root) break;
      const t = heap[root];
      heap[root] = heap[smallest];
      heap[smallest] = t;
      root = smallest;
    }
  }
  let size = n;
  for (let out = 0; out < n; out++) {
    arr[out] = heap[0];
    size--;
    heap[0] = heap[size];
    let root = 0;
    while (true) {
      let smallest = root;
      const l = 2 * root + 1;
      const r = 2 * root + 2;
      if (l < size && heap[l] < heap[smallest]) smallest = l;
      if (r < size && heap[r] < heap[smallest]) smallest = r;
      if (smallest === root) break;
      const t = heap[root];
      heap[root] = heap[smallest];
      heap[smallest] = t;
      root = smallest;
    }
  }
}