Pancake Sort in Java
Learn how Pancake Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Pancake Sort is a comparison sort with an unusual rule: the only way to change the order is a flip, which reverses the top of the stack. Picture a stack of pancakes of different sizes and a spatula. You can slide the spatula under any pancake and flip everything above it over in one go, but you can’t pull a pancake out of the middle.
Three ideas carry the whole algorithm:
- Prefix flip:
flip(k)reverses the firstk + 1values, from index 0 (the top of the stack) to indexk. - Largest to the bottom: find the largest unsorted pancake, flip it to the top, then flip the whole unsorted part so it lands at the bottom.
- Shrinking stack: once the largest pancake is at the bottom, it is never touched again, and the same two flips repeat on the rest.
Pancake sorting started as a puzzle, posed in 1975 under the pen name Harry Dweighter (“harried waiter”): how many flips does it take to sort a stack of $n$ pancakes? In 1979, Bill Gates and Christos Papadimitriou published an upper bound of $(5n + 5) / 3$ flips, the only research paper Gates ever wrote. The puzzle matters beyond breakfast: prefix reversals model mutations in genome rearrangement, and the “pancake graph” is used to design networks that connect processors.
This article explains Pancake Sort with prefix flips, which uses at most $2n - 3$ flips. The Java code in the repository uses a shortcut that reverses a segment in the middle of the stack instead; the Java section shows where it differs.
Performance Characteristics
Pancake Sort is usually measured in two ways: the number of flips, which is what the puzzle counts, and the number of operations a computer makes to perform them.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n^2)$ | An already sorted array: no flips are needed, but every round still searches for the maximum |
| Average | $O(n^2)$ | Random input |
| Worst | $O(n^2)$ | Any input: up to $2n - 3$ flips, each moving up to $n$ values |
Why $n^2$? Each round scans the unsorted part to find the largest pancake, which is $O(n)$ comparisons, and makes up to two flips, each reversing up to $n$ values. There are $n - 1$ rounds, so both the comparisons and the moves add up to $O(n^2)$. The number of flips is only $O(n)$: at most two per round, and none for a round whose largest pancake is already at the bottom.
Pancake Sort is a puzzle and a model, not a practical sort. When reversing a prefix is the only operation available, it is the right tool; otherwise, any $O(n \log n)$ sort is faster, and even insertion sort moves fewer values.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(1)$: a few indices; flips swap values in place |
| In place | Yes |
| Stable | No (a flip reverses the order of everything it moves) |
Algorithm (Pseudo Code)
Pancake Sort starts with the whole stack unsorted. It looks through the unsorted part for the largest pancake. If that pancake is already at the bottom of the unsorted part, it is in place. Otherwise, the spatula goes under it and the top of the stack is flipped, which brings the largest pancake to the top. Then the spatula goes under the last unsorted pancake and the whole unsorted part is flipped, which carries the largest pancake from the top to the bottom.
The bottom of the unsorted part now holds its largest pancake, so the unsorted part shrinks by one, and the same steps repeat on the smaller stack. When only one pancake is left unsorted, it is the smallest, it is on top, and the whole stack is sorted.
1
2
3
4
5
6
7
8
9
10
11
pancakeSort(array):
for end = n - 1 down to 1:
maxIndex = index of the largest value in array[0 .. end]
if maxIndex != end:
if maxIndex != 0:
flip(array, 0, maxIndex) // largest to the top
flip(array, 0, end) // top to the bottom of the unsorted part
return array
flip(array, left, right):
while left <= right: swap(left++, right--)
After each round, array[end .. n - 1] holds the largest values in their final, sorted positions.
The Java code below calls
flip(array, maxIndex, end): it reverses the segment from the largest pancake to the end of the unsorted part in one reversal. That also moves the largest value toend, and the array still ends up sorted, but the segment doesn’t start at the top of the stack, so it isn’t a pancake flip. The warning in thesortsection explains the difference.
Visualization
The visualization below follows the algorithm step by step, starting with the values 0 to 9 in shuffled order, drawn as a stack of pancakes with index 0 on top.
By default it uses real prefix flips, as in the pseudo code. Tick Flip as in the code to see the single segment reversal that the Java code makes instead.
Each step shows the stack, the range about to be flipped or just flipped, and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Stack: each pancake’s width is its value, and its index is on the left. Pancakes below the unsorted part fade while the largest is searched for.
- Bracket: the bracket on the left marks the range that the next flip will reverse, or that it just reversed. With real flips, it always starts at the top.
- Colours: the largest unsorted pancake is amber, the pancakes that were just flipped are salmon, and pancakes in their final place at the bottom are green.
- Flips: the footer counts the flips.
Java Code
The implementation is a PancakeSort class with one public method, sort, and one private method, findIndexOfMax, which finds the largest value in the unsorted part. The reversal is the flip helper, which lives in the SortUtils class together with swap and less.
The complete code is in the algorithm-examples repository on GitHub:
PancakeSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length < 2) {
return array;
}
for (int currentSize = 0; currentSize < array.length; currentSize++) {
int maxIndex = findIndexOfMax(array, currentSize);
SortUtils.flip(array, maxIndex, array.length - 1 - currentSize);
}
return array;
}
sort is the entry point. It accepts an array of any Comparable type and returns arrays with fewer than two values straight back. currentSize counts how many values are already in place at the end. Each round finds the largest value in the unsorted part and reverses the segment from it to the last unsorted index, which puts the largest value at that index. The array is sorted in place and returned.
This is not a pancake flip. A pancake flip always starts at the top of the stack, index 0, but
flip(array, maxIndex, end)starts atmaxIndex, in the middle. The result is still correct, since the largest value always lands atend; on 20,000 random arrays, the code sorts every one. But it skips the defining rule of the puzzle, and its flip counts don’t answer the pancake question: on the visualization’s data it makes 10 reversals, where a real pancake sort needs 15 flips. Replacing the single call withflip(array, 0, maxIndex)followed byflip(array, 0, end)turns it into the real algorithm.
Two details are worth noticing:
- The loop runs
array.lengthtimes, so the last round reverses a single value, which changes nothing. Running toarray.length - 1would be enough. - The code always flips, even when the largest value is already at
end; then the segment has one value and the flip does nothing, but it still costs a call.
findIndexOfMax
1
2
3
4
5
6
7
8
9
10
11
private <T extends Comparable<T>> int findIndexOfMax(T[] array, int currentSize) {
T max = array[0];
int maxIndex = 0;
for (int i = 0; i < array.length - currentSize; i++) {
if (SortUtils.less(max, array[i])) {
max = array[i];
maxIndex = i;
}
}
return maxIndex;
}
findIndexOfMax scans the unsorted part, array[0 .. array.length - currentSize - 1], and keeps the largest value seen so far. Because the comparison is strict, it returns the first index of the largest value when there are ties.
flip, swap and less
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static <T extends Comparable<T>> void flip(T[] array, int left, int right) {
while (left <= right) {
swap(array, left++, right--);
}
}
public static <T> void swap(T[] array, int i, int j) {
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
flip reverses array[left .. right] by swapping the two ends and moving inward until they meet. With left = 0, it is a pancake flip; with any other left, it reverses a segment in the middle. swap exchanges two elements, and less compares two elements with compareTo, so the algorithm works for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new PancakeSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a PancakeSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Pancake Sort sorts using only prefix flips: reversals of the top of the stack, like flipping pancakes with a spatula.
- Each round flips the largest unsorted pancake to the top, then flips the whole unsorted part to carry it to the bottom, using at most $2n - 3$ flips in total.
- After each round, the largest remaining value is in its final place at the bottom, and the unsorted stack shrinks by one.
- It needs $O(n)$ flips but $O(n^2)$ comparisons and moves, uses $O(1)$ extra space, and is in place but not stable.
- The Java code reverses a middle segment instead of a prefix; it sorts correctly but isn’t a true pancake sort. For real data, use an $O(n \log n)$ sort such as
Arrays.sort().
