Algorithm Visualiser by Tsvetozar Biserov

Pancake Sort

  • Ω( n2 )
  • Θ( n2 )
  • O( n2 )
  • space O( 1 )

Pancake sort lives under one rule: the only thing you may do is take a prefix of the array and reverse it, as a cook slides a spatula under the top of a stack and flips it. To fix the biggest unsorted value, flip it up to the front, then flip the whole unsorted prefix to drop it at the bottom. It is a puzzle first and a sorting method second, but its flip counts are a real research topic.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How pancake sort works

On 5, 2, 6, 1, 4, 3 the largest value is the 6 at index 2. A flip of the first three cells exchanges indices 0 and 2, giving [6, 2, 5, 1, 4, 3]. Now the whole six-cell prefix is flipped, and the page shows it as three swaps: first the ends, [3, 2, 5, 1, 4, 6], then the next pair, [3, 4, 5, 1, 2, 6], then the middle pair, [3, 4, 1, 5, 2, 6]. The 6 is in its final cell after four swaps, and the rest of the array is scrambled but smaller.

The second round looks at the prefix 3, 4, 1, 5, 2. Its maximum 5 sits at index 3. Flipping four cells takes two swaps, [5, 4, 1, 3, 2, 6] and then [5, 1, 4, 3, 2, 6], and flipping five cells takes two more, [2, 1, 4, 3, 5, 6] and then [2, 3, 4, 1, 5, 6]. The third round finds the 4 at index 2 and flips three cells, giving [4, 3, 2, 1, 5, 6]. Flipping four cells then passes through [1, 3, 2, 4, 5, 6] and ends at [1, 2, 3, 4, 5, 6].

That is eleven swaps and the array is sorted, yet the algorithm is not finished. The remaining two rounds each scan their prefix, see that the maximum is already at the bottom and skip the flips, which adds the last comparisons. The total of 15 comparisons is exactly 5 + 4 + 3 + 2 + 1, because each round scans its whole prefix to find the maximum whether or not any flip follows.

Pancake Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Swap indexes 0 and 2 6 2 5 1 4 3
2 Swap indexes 0 and 5 3 2 5 1 4 6
3 Swap indexes 1 and 4 3 4 5 1 2 6
4 Swap indexes 2 and 3 3 4 1 5 2 6
5 Swap indexes 0 and 3 5 4 1 3 2 6
6 Swap indexes 1 and 2 5 1 4 3 2 6
7 Swap indexes 0 and 4 2 1 4 3 5 6
8 Swap indexes 1 and 3 2 3 4 1 5 6
9 Swap indexes 0 and 2 4 3 2 1 5 6
10 Swap indexes 0 and 3 1 3 2 4 5 6
11 Swap indexes 1 and 2 1 2 3 4 5 6

All 11 changes are shown.

Pseudocode

for size = n down to 2
  m = index of the largest element in a[0 .. size - 1]
  if m == size - 1
    continue
  if m > 0
    flip(m)
  flip(size - 1)

flip(k)
  reverse a[0 .. k]

Why these complexities

The maximum search reads the entire unsorted prefix, so round k costs size - 1 comparisons and the total is n(n-1)/2 for every input. Sorted, reversed or random arrays of eight elements all show 28. This is why best, average and worst are all O(n²) and why the algorithm cannot be adaptive in the usual sense: nothing in the scan can end early.

The flips are the other cost. This implementation spends at most two per round, one to bring the maximum to index 0 and one to send it to the bottom of the prefix. It skips the first when the maximum is already at the front and skips both when it is already in place. The last round of two cells needs at most one flip, so the worst case is 2n - 3 flips. A flip of length L is drawn as about L / 2 swaps, so a bad input needs on the order of n²/2 swaps in total, and that matches the comparison cost.

Space is O(1): a few indices and the current maximum. The flips happen in place by exchanging mirrored pairs. Equal values are not kept in order. The scan picks the leftmost maximum, and the two flips that carry it down also reverse the order of everything they touch, so equal elements regularly change places.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 496 0 331
Already sorted 496 0 0
Reversed 496 0 16
Few distinct values 496 0 314

When to use it

Use it as a puzzle or a teaching example for sorting with a single operation, the prefix reversal. It has no practical use for ordinary sorting.

Frequently asked questions

What is a flip?

A flip reverses the first k elements of the array, like sliding a spatula under the top k pancakes and turning them over.

How many flips does it need?

At most about 2n flips, two per element: one to bring the largest to the front and one to send it to its place.

Why is the total O(n²)?

Each flip costs up to n element moves and there are O(n) flips, plus the search for the largest element in every pass.

Is 2n flips the best a pancake sorter can do?

No. The strategy on this page is simple but wasteful, since it brings every maximum to the front first. Smarter strategies look at which pancakes are already adjacent in sorted order and avoid separating them. Gates and Papadimitriou showed that (5n + 5) / 3 flips always suffice, and later work lowered the bound to 18n / 11. The true worst case is known exactly only for small stacks.

Why does a reversed array take almost no work while a scrambled one takes many swaps?

On a reversed array the maximum is already at index 0, so the first round skips the opening flip and a single flip of the whole array sorts it. For eight elements that is four swaps, and every later round finds its maximum in place. Sorted input needs no flips at all. Comparisons are unaffected: all three cases still cost 28, so the saving lies entirely in the writes.

Background

The pancake problem was posed in 1975 in the American Mathematical Monthly by Jacob E. Goodman under the pseudonym Harry Dweighter, a pun on a harried waiter: how many flips are always enough to sort a stack of n pancakes of different sizes? The simple strategy used here gives 2n - 3, and the question is how much better is possible.

In 1979 William Gates and Christos Papadimitriou proved that (5n + 5) / 3 flips always suffice and that some stacks need at least 17n / 16. Gates is the same person who later co-founded Microsoft. The upper bound was lowered to 18n / 11 in 2009, and the exact worst case is still unknown for most n. The variant in which each pancake also has a burnt side that must end face down has been studied just as intensively.

References

  • Gates and Papadimitriou, Bounds for sorting by prefix reversal, Discrete Mathematics 27(1), 1979
  • Dweighter (J. E. Goodman), Problem E2569, American Mathematical Monthly 82, 1975
  • Chitturi, Fahle, Meng, Morales, Shields, Sudborough, Voit, An (18/11)n upper bound for sorting by prefix reversals, Theoretical Computer Science 410, 2009

Compare with

Algorithm Average time Worst time
Selection Sort Θ( n2 ) O( n2 )
Heap Sort Θ( n log n ) O( n log n )
Cycle Sort Θ( n2 ) O( n2 )
Big O notation
Best time Ω( n2 ) poor
Average time Θ( n2 ) poor
Worst time O( n2 ) poor
Worst space O( 1 ) good

Properties

Stable
No
In place
Yes
Adaptive
No
Comparison-based
Yes