Pancake Sorting in C++


Suppose we have an array A, we will perform the Pancake sort technique on A. Here the main constraint is that we can use only one operation called rev(arr, i). This will reverse the elements of arr from 0 to ith position. This idea is like the selection sort. We repeatedly place the max element at end reduce the size of the array. So if the input is like [54,85,52,25,98,75,25,11,68], then the result will be [11,25,25,52,54,68,75,85,98]

To solve this, we will follow these steps −

  • size := n

  • while size > 1, do

    • index := index of max element in arr from [0 to size – 1]

    • rev(arr, index)

    • rev(arr, size - 1)

    • size := size - 1

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include<iostream>
using namespace std;
void rev(int arr[], int i) {
   int temp, st = 0;
   while (st < i) {
      temp = arr[st];
      arr[st] = arr[i];
      arr[i] = temp;
      st++;
      i--;
   }
}
int maxIndex(int arr[], int n) {
   int index, i;
   for (index = 0, i = 0; i < n; ++i){
      if (arr[i] > arr[index]) {
         index = i;
      }
   }
   return index;
}
int pancakeSort(int arr[], int n) {
   for (int size = n; size > 1; size--) {
      int index = maxIndex(arr, size);
      if (index != size-1) {
         rev(arr, index);
         rev(arr, size-1);
      }
   }
}
int main() {
   int arr[] = {54, 85, 52, 25, 98, 75, 25, 11, 68};
   int n = sizeof(arr)/sizeof(arr[0]);
   pancakeSort(arr, n);
   cout << "Sorted array: ";
   for (int i = 0; i < n; ++i)
   cout << arr[i] << " ";
}

Input

[54, 85, 52, 25, 98, 75, 25, 11, 68]

Output

[11,25,25,52,54,68,75,85,98]

Updated on: 02-May-2020

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements