In-Place Merge Sort

Merge-based sorting using in-place gap-merge strategy to minimize auxiliary memory.

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

How it works

Merge-based sorting using in-place gap-merge strategy to minimize auxiliary memory.

Implementation

function inPlaceMergeSort(arr, stats) {
  const n = arr.length;
  function nextGap(gap) {
    if (gap <= 1) return 0;
    return (gap >> 1) + (gap & 1);
  }
  function mergeInPlace(left, mid, right) {
    for (let gap = nextGap(right - left + 1); gap > 0; gap = nextGap(gap)) {
      for (let i = left; i + gap <= right; i++) {
        const j = i + gap;
        compare(i, j);
        if (arr[i] > arr[j]) {
          swap(i, j);
          const t = arr[i];
          arr[i] = arr[j];
          arr[j] = t;
        }
      }
    }
  }
  function sort(lo, hi) {
    if (lo >= hi) return;
    const mid = lo + hi >> 1;
    sort(lo, mid);
    sort(mid + 1, hi);
    mergeInPlace(lo, mid, hi);
  }
  sort(0, n - 1);
}