Typorithm · medium

Pancake Sort

▷ Interactive algorithm labpancake-sortsortingprefix-reversalselectionquadratic-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Pancake Sort

0%

Sorting Algorithms

Pancake Sort repeatedly uses prefix reversals to move the largest active value into place.

The only operation in Pancake Sort is flipping a prefix of the array.

Each pass scans the active prefix to find its largest value.

One flip brings that value to the front; another flip moves it to the end of the active prefix.

The active size shrinks because the largest value is now fixed in the sorted tail.

The algorithm is educational and constraint-driven, with O(n^2) time.

Preparing algorithm lab…
01

Find the max in the active prefix.

02

Flip max to the front.

03

Flip max into final position.

04

Shrink the active size.

05

Uses prefix reversals instead of arbitrary swaps.

function pancakeSort(arr) {
  for (let size = arr.length; size > 1; size--) {
    let maxIndex = 0;

    for (let i = 1; i < size; i++) {
      if (arr[i] > arr[maxIndex]) {
        maxIndex = i;
      }
    }

    if (maxIndex === size - 1) continue;

    flip(arr, maxIndex);
    flip(arr, size - 1);
  }

  return arr;
}

function flip(arr, end) {
  let start = 0;

  while (start < end) {
    [arr[start], arr[end]] = [arr[end], arr[start]];
    start++;
    end--;
  }
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Active stack size

Each pass places the maximum of the active prefix at size - 1.

for (let size = arr.length; size > 1; size--)

2. Max candidate

Start by assuming the active prefix begins with the largest value.

let maxIndex = 0

3. Find max

Scan only the active unsorted prefix.

for (let i = 1; i < size; i++)

4. Update max

Remember where the largest active value is.

maxIndex = i

5. Already placed

If the largest active value is already at the end, no flips are needed.

if (maxIndex === size - 1) continue

6. Bring max to top

Flip the max value to the front of the array.

flip(arr, maxIndex)

7. Place max

Flip it from the front into its final active end position.

flip(arr, size - 1)

8. Reverse prefix

The helper reverses values from index 0 through end.

while (start < end)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Pancake Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn