# A Pancake Sorting Problem?

CServer Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 12:06:03