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, stats) {
  const n = arr.length;
  function flip(k) {
    let left = 0, right = k;
    while (left < right) {
      [arr[left], arr[right]] = [arr[right], arr[left]];
      swap(left, right);
      left++;
      right--;
    }
  }
  for (let size = n; 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);
    }
    checkpoint(n - size, n - 1);
  }
}