# C program to implement Pancake sort algorithm

Here, we are going to learn how to implement Pancake sort algorithm using C program?
Submitted by Nidhi, on August 17, 2021

Problem Solution:

Here, we will create an array of integers then we will read array elements from the user and implement the Pancake sort algorithm to arrange array elements in ascending order.

Program:

The source code to implement the Pancake sort algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to implement Pancake sort algorithm

#include <stdio.h>
#include <stdlib.h>

void flipItems(int arr[], int length, int num)
{
int temp;
int i = 0;

while (i < --num) {
temp = arr[i];
arr[i] = arr[num];
arr[num] = temp;
i++;
}
}

int panCakeSort(int* arr, unsigned int len)
{
int i = 0;
int j = 0;
int max = 0;
int moves = 0;

if (len < 2)
return 0;

i = len;
while (i > 1) {
max = 0;
j = 0;
while (j < i) {
if (arr[j] > arr[max])
max = j;
j++;
}
if (max == i - 1) {
i--;
continue;
}

if (max) {
moves++;
flipItems(arr, len, max + 1);
}

flipItems(arr, len, i);
i--;
}
return moves;
}

int main()
{
int i = 0;
int moves = 0;

int arr;

printf("Enter array elements:\n");
while (i < 5) {
printf("Element[%d]: ", i);
scanf("%d", &arr[i]);
i++;
}

moves = panCakeSort(arr, 5);

printf("Sorted Array: \n");
i = 0;
while (i < 5) {
printf("%d ", arr[i]);
i++;
}
printf("\nTotal moves are: %d\n", moves);

return 0;
}
```

Output:

```RUN 1:
Enter array elements:
Element: 12
Element: 45
Element: 10
Element: 5
Element: 2
Sorted Array:
2 5 10 12 45
Total moves are: 1

RUN 2:
Enter array elements:
Element: 43
Element: 23
Element: 76
Element: 45
Element: 65
Sorted Array:
23 43 45 65 76
Total moves are: 1
```

Explanation:

Here, we created three functions flipItems(), panCakeSort(), and main(). The flipItems() function is used to swap items. The panCakeSort() function is used to sort array elements.

In the main() function, we read array elements from the user. Then we sorted the elements of the array in ascending order using the panCakeSort () function and print the sorted array as well as the total number of moves on the console screen.

Preparation

What's New

Top Interview Coding Problems/Challenges!