Pancake Sort

Sorts by repeatedly flipping sub-arrays, like arranging pancakes by size. Only uses a "flip" operation (reversing a prefix of the array).

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

How it works

Sorts by repeatedly flipping sub-arrays, like arranging pancakes by size. Only uses a "flip" operation (reversing a prefix of the array).

Implementation

function pancakeSort(arr) {
  function flip(end) {
    let l = 0, r = end;
    while (l < r) { [arr[l], arr[r]] = [arr[r], arr[l]]; l++; r--; }
  }
  for (let size = arr.length; size > 1; size--) {
    let maxIdx = 0;
    for (let i = 1; i < size; i++)
      if (arr[i] > arr[maxIdx]) maxIdx = i;
    if (maxIdx !== size - 1) {
      if (maxIdx > 0) flip(maxIdx);
      flip(size - 1);
    }
  }
}