Batchers Odd-Even Mergesort

Sorting network style.

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

How it works

Sorting network style.

Implementation

function oddEvenMergeSort(arr) {
  function merge(lo, hi, step) {
    let s2 = step * 2;
    if (s2 >= hi - lo) {
      if (lo + step < hi && arr[lo] > arr[lo+step])
        [arr[lo], arr[lo+step]] = [arr[lo+step], arr[lo]];
      return;
    }
    merge(lo, hi, s2);
    merge(lo + step, hi, s2);
    for (let i = lo+step; i+step < hi; i += s2)
      if (arr[i] > arr[i+step])
        [arr[i], arr[i+step]] = [arr[i+step], arr[i]];
  }
  function sort(lo, hi) {
    if (hi - lo <= 1) return;
    let mid = (lo + hi) >> 1;
    sort(lo, mid); sort(mid, hi);
    merge(lo, hi, 1);
  }
  sort(0, arr.length);
}