Circle Sort

Compares elements equidistant from both ends, swapping if out of order. Repeats until no swaps needed. Simple and elegant.

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

How it works

Compares elements equidistant from both ends, swapping if out of order. Repeats until no swaps needed. Simple and elegant.

Implementation

function circleSort(arr) {
  function circlePass(lo, hi) {
    if (lo >= hi) return false;
    let swapped = false, l = lo, r = hi;
    while (l < r) {
      if (arr[l] > arr[r]) {
        [arr[l], arr[r]] = [arr[r], arr[l]];
        swapped = true;
      }
      l++; r--;
    }
    let mid = (lo + hi) >> 1;
    swapped = circlePass(lo, mid) || swapped;
    swapped = circlePass(mid+1, hi) || swapped;
    return swapped;
  }
  while (circlePass(0, arr.length - 1));
}