Bottom-Up Merge Sort

Iterative merge sort that merges runs of doubling size without recursion.

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

How it works

Iterative merge sort that merges runs of doubling size without recursion.

Implementation

function bottomUpMergeSort(arr, stats) {
  const n = arr.length;
  const tmp = new Array(n);
  for (let width = 1; width < n; width <<= 1) {
    for (let left = 0; left < n; left += width << 1) {
      const mid = Math.min(left + width, n);
      const right = Math.min(left + (width << 1), n);
      let i = left;
      let j = mid;
      let k = left;
      while (i < mid && j < right) {
        compare(i, j);
        if (arr[i] <= arr[j]) tmp[k++] = arr[i++]; else tmp[k++] = arr[j++];
      }
      while (i < mid) {
        tmp[k++] = arr[i++];
      }
      while (j < right) {
        tmp[k++] = arr[j++];
      }
      for (let p = left; p < right; p++) {
        arr[p] = tmp[p];
        write(p, arr[p]);
      }
    }
  }
}