Add

C program to implement Pancake sort algorithm




Explanation:

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. 

// 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[5];

    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[0]: 12

Element[1]: 45

Element[2]: 10

Element[3]: 5

Element[4]: 2

Sorted Array:

2 5 10 12 45

Total moves are: 1

 

RUN 2:

Enter array elements:

Element[0]: 43

Element[1]: 23

Element[2]: 76

Element[3]: 45

Element[4]: 65

Sorted Array:

23 43 45 65 76

Total moves are: 1


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.