Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
A Pancake Sorting Problem?
Pancake sorting is a unique sorting algorithm that mimics the process of sorting a stack of pancakes by flipping portions of the stack. In this algorithm, we can only use one operation: rev(arr, i), which reverses elements from index 0 to index i. The goal is to sort the entire array using only this flip operation.
The algorithm works similarly to selection sort − we repeatedly find the largest element and move it to its correct position at the end of the current unsorted portion.
Syntax
void rev(int arr[], int i); int maxIndex(int arr[], int n); void pancakeSort(int arr[], int n);
Algorithm
pancakeSort(arr, n)
Begin
size := n
while size > 1, do
index := index of max element in arr from [0 to size - 1]
if index != size-1 then
rev(arr, index) // Move max to front
rev(arr, size - 1) // Move max to correct position
end if
size := size - 1
done
End
How It Works
The pancake sort algorithm follows these steps −
- Step 1: Find the maximum element in the current unsorted portion
- Step 2: If it's not already at the front, flip the array to bring it to position 0
- Step 3: Flip the array again to move the maximum element to its final sorted position
- Step 4: Reduce the array size and repeat
Example
#include <stdio.h>
void rev(int arr[], int i) {
int temp, start = 0;
while (start < i) {
temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
start++;
i--;
}
}
int maxIndex(int arr[], int n) {
int index = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[index]) {
index = i;
}
}
return index;
}
void pancakeSort(int arr[], int n) {
for (int size = n; size > 1; size--) {
int index = maxIndex(arr, size);
if (index != size - 1) {
rev(arr, index); /* Move max to front */
rev(arr, size - 1); /* Move max to position */
}
}
}
int main() {
int arr[] = {54, 85, 52, 25, 98, 75, 25, 11, 68};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("
");
pancakeSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("
");
return 0;
}
Original array: 54 85 52 25 98 75 25 11 68 Sorted array: 11 25 25 52 54 68 75 85 98
Key Points
- Time Complexity: O(n²) where n is the number of elements
- Space Complexity: O(1) as it sorts in-place
- At most 2n flips are needed to sort n elements
- The algorithm is not stable (relative order of equal elements may change)
Conclusion
Pancake sorting demonstrates an interesting approach to sorting using only flip operations. While not the most efficient sorting algorithm, it provides valuable insights into problem-solving with limited operations and has practical applications in computational biology.
