UNUSUAL STRUCTURES
Pancake Sort, visualised
Pancake sort orders the array using only one operation: reversing the prefix from the front up to position k — like flipping a stack of pancakes with a spatula.
Run Pancake Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Find the position of the maximum in the unsorted part.
- If it is not at the front, flip the prefix up to it so the maximum comes to the front.
- Flip the whole unsorted part so the maximum goes to its end.
- Shrink the unsorted part by one and repeat (no flips if the maximum is already at the end).
Complexity and stability
- Best
- O(n²)
- Average
- O(n²)
- Worst
- O(n²)
- Extra space
- O(1)
- Stability
- Usually unstable
Each round scans the rest for the maximum, so comparisons are O(n²) for any input. Each round uses at most two flips, and a flip takes up to O(n) swaps.
Source of facts: Complexity is derived from the steps of this app's implementation (src/SortingCinema.jsx).
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Compare [0]=5 and [1]=2 | [5, 2, 4, 1, 3] |
| 2 | Compare [0]=5 and [2]=4 | [5, 2, 4, 1, 3] |
| 3 | Compare [0]=5 and [3]=1 | [5, 2, 4, 1, 3] |
| 4 | Compare [0]=5 and [4]=3 | [5, 2, 4, 1, 3] |
| 5 | Swap [0]=5 and [4]=3 | [3, 2, 4, 1, 5] |
| 6 | Swap [1]=2 and [3]=1 | [3, 1, 4, 2, 5] |
| 7 | Compare [0]=3 and [1]=1 | [3, 1, 4, 2, 5] |
| 8 | Compare [0]=3 and [2]=4 | [3, 1, 4, 2, 5] |
…and so on. In this trace, 17 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Watch it as a puzzle where flipping is the only allowed move.
- In the visualisation, a flip appears as swaps moving inward from both ends.
- Flips rearrange large chunks, so it is usually unstable.
FAQ
How many flips are needed?
In this app's procedure, at most two per round, and none in rounds where the maximum is already in place.
What does it share with selection sort?
Both find the maximum (or minimum) of the unsorted part and move it to an end; pancake sort does so by flipping instead of swapping.