A Pancake Sorting Problem?


Here we will see another sorting problem named Pancake sort. This problem is simple. We have one array. We have to sort this. But 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. Let us see the algorithm to get the idea.

Algorithm

pancakeSort(arr, n)

Begin
   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
   done
End

Example

#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] << " ";
}

Output

Sorted array: 11 25 25 52 54 68 75 85 98

Updated on: 31-Jul-2019

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements