Javatpoint Logo
Javatpoint Logo

Pancake sorting in C++

In this article, we will discuss pancake sorting in C++ with their examples.

When a spatula may be inserted at any position in the stack and used to flip every pancake above it, the mathematics issue of sorting a disorganized stack of pancakes in order of size is known as pancake sorting. The minimal amount of flips needed to make a certain quantity of pancakes is known as a pancake number.

Its main goal is to act similarly to the selection sort. We gradually reduce the size of the current array by one by adding the largest member at the end.

Program Explanation:

  1. Create a method called flip(Arr, i) that flips the order of the array arr's first i members.
  2. Create the function pancakeSort(Arr), which returns the input array sorted. You can use only the flip function to make changes in the array.


Let the given array be Arr[] and the size of the array be 'n'.

Start from the current size 'n' and reduce the current size by one while it is greater than one. Let the current size be c. Do the following for every 'c'.

  1. Find the index 'i' of the maximum element in Arr[0....c-1].
  2. Call flip(Arr,i)
  3. Call flip(Arr,c-1)


Let's take an example to demonstrate the pancake sorting in C++:


Pancake sorting in C++


Time Complexity:

The pancake sorting algorithm has an O(n2) time complexity, where 'n' is the number of elements in the input array.

The largest element may require up to n flips (reversals) to reach the top of the stack in the worst case, followed by n-1 flips to move the second-largest element to the second slot, etc. As a result, the temporal complexity is quadratic.

Space Complexity:

The pancake sorting algorithm has an O(1) space complexity, which indicates that regardless of the input size, it always requires a fixed amount of extra memory.

An in-place sorting algorithm, pancake sorting, sort the elements in the initial array without using more memory in proportion to the input size.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA