Algorithms · Visualized
Pancake Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Pancake sort allows only one operation — flipping (reversing) a prefix of the array, like flipping a stack of pancakes with a spatula. Time: O(n²) average, O(n²) with up to 2n flips worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Pancake Sort
SortingPancake sort allows only one operation — flipping (reversing) a prefix of the array, like flipping a stack of pancakes with a spatula. It repeatedly finds the largest unsorted element, flips it to the front, then flips the whole unsorted prefix so that element lands in its final position at the back.
How Pancake Sort Works
- In the current unsorted portion [0..size-1], find the index of the maximum element.
- Flip the prefix from 0 to that index, bringing the maximum to the front.
- Flip the prefix from 0 to size-1, dropping the maximum into its final position at the end.
- Shrink the unsorted portion by one and repeat until only one element remains unsorted.
Pancake Sort Worked Example
Input: [3, 1, 4, 2]
Size 4: max is 4 at index 2 → flip prefix 0..2 → [4,1,3,2] → flip prefix 0..3 → [2,3,1,4]. Size 3: max is 3 at index 1 → flip 0..1 → [3,2,1,4] → flip 0..2 → [1,2,3,4]. Size 2: max is 2 at index 1 → flip 0..1 → [2,1,3,4] → flip 0..1 → [1,2,3,4]. Done.
def pancake_sort(a):
n = len(a)
for size in range(n, 1, -1):
mi = 0
for i in range(1, size):
if a[i] > a[mi]:
mi = i
if mi != size - 1:
a[:mi + 1] = reversed(a[:mi + 1])
a[:size] = reversed(a[:size])
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Pancake Sort Time & Space Complexity
When to Use Pancake Sort
- Teaching algorithm analysis with heavily restricted operations.
- Modeling genome rearrangement by reversal distance.
- Robotic/manual sorting where only prefix flips are possible.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.