Open In App

Java Program for Pancake sorting

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a Java program for a given unsorted array, the task is to sort the given array. You are allowed to do only the following operation on the array.

  • flip(arr, i): Reverse array from 0 to i.

Examples:

Input: arr[] = { 23, 10, 20, 11, 12, 6, 7 }
Output: { 6, 7, 10, 11, 12, 20, 23}

Input: arr[] = { 0, 1, 1, 0, 0 }
Output: { 0, 0, 0, 1, 1 }

Approach: Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons possible, the goal is to sort the sequence in as few reversals as possible.

The idea is to do something similar to Selection Sort. We one by one place maximum element at the end and reduce the size of current array by one.

Step-step-step approach:

  • Let the given array be arr[] and the size of the array be n.
  • Start from the current size equal to n and reduce the current size by one while it’s greater than 1. Let the current size be curr_size.
  • Do the following for every curr_size
    • Find an index of the maximum element in arr[0 to curr_szie-1]. Let the index be ‘mi’
    • Call flip(arr, mi)
    • Call flip(arr, curr_size – 1)

Below is the implementation of the above approach:

Java




// Java program to
// sort array using
// pancake sort
import java.io.*;
 
class PancakeSort {
 
    /* Reverses arr[0..i] */
    static void flip(int arr[], int i)
    {
        int temp, start = 0;
        while (start < i) {
            temp = arr[start];
            arr[start] = arr[i];
            arr[i] = temp;
            start++;
            i--;
        }
    }
 
    // Returns index of the
    // maximum element in
    // arr[0..n-1]
    static int findMax(int arr[], int n)
    {
        int mi, i;
        for (mi = 0, i = 0; i < n; ++i)
            if (arr[i] > arr[mi])
                mi = i;
        return mi;
    }
 
    // The main function that
    // sorts given array using
    // flip operations
    static int pancakeSort(int arr[], int n)
    {
        // Start from the complete
        // array and one by one
        // reduce current size by one
        for (int curr_size = n; curr_size > 1;
             --curr_size) {
            // Find index of the
            // maximum element in
            // arr[0..curr_size-1]
            int mi = findMax(arr, curr_size);
 
            // Move the maximum element
            // to end of current array
            // if it's not already at
            // the end
            if (mi != curr_size - 1) {
                // To move at the end,
                // first move maximum
                // number to beginning
                flip(arr, mi);
 
                // Now move the maximum
                // number to end by
                // reversing current array
                flip(arr, curr_size - 1);
            }
        }
        return 0;
    }
 
    /* Utility function to print array arr[] */
    static void printArray(int arr[], int arr_size)
    {
        for (int i = 0; i < arr_size; i++)
            System.out.print(arr[i] + " ");
        System.out.println("");
    }
 
    /* Driver function to check for above functions*/
    public static void main(String[] args)
    {
        int arr[] = { 23, 10, 20, 11, 12, 6, 7 };
        int n = arr.length;
 
        pancakeSort(arr, n);
 
        System.out.println("Sorted Array: ");
        printArray(arr, n);
    }
}
/* This code is contributed by Devesh Agrawal*/


Output

Sorted Array: 
6 7 10 11 12 20 23 

Time Complexity: O(n2), Total O(n) flip operations are performed in above code
Auxiliary Space: O(1)

Java Program for Pancake sorting using Recursion:

  • Define a function to flip a subarray of the given array. This function takes two arguments: the array to be flipped, and the index of the last element of the subarray to be flipped.
  • Define a function to find the index of the maximum element in a given subarray of the array. This function takes two arguments: the array to be searched, and the index of the last element of the subarray to be searched.
  • Iterate over the input array from the end towards the beginning, and for each element i, do the following:
    • Find the index of the maximum element in the subarray arr[0:i].
    • If the maximum element is not already at the end of the subarray, flip the subarray arr[0:max_index].
    • Flip the entire subarray arr[0:i] to move the element i to its correct position.
  • Repeat 3 steps for the subarray arr[0:n-1], arr[0:n-2], …, arr[0:1] until the entire array is sorted.

Below is the implementation of the above approach:

Java




import java.util.*;
 
public class PancakeSort {
    // Reverses arr[0..i]
    static void flip(int arr[], int i)
    {
        int temp, start = 0;
        while (start < i) {
            temp = arr[start];
            arr[start] = arr[i];
            arr[i] = temp;
            start++;
            i--;
        }
    }
 
    // Recursive function to sort the array using pancake
    // sort
    static void pancakeSort(int arr[], int n)
    {
        // Base case: If the array is already sorted or has
        // only one element, return
        if (n == 1)
            return;
 
        // Find the index of the maximum element in the
        // unsorted portion of the array
        int mi = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] > arr[mi]) {
                mi = i;
            }
        }
 
        // Move the maximum element to the front of the
        // array if it's not already there
        if (mi != 0) {
            flip(arr, mi);
        }
 
        // Flip the entire array to move the maximum element
        // to its correct position
        flip(arr, n - 1);
 
        // Recursively sort the remaining unsorted portion
        // of the array
        pancakeSort(arr, n - 1);
    }
 
    // Driver program to test above function
    public static void main(String args[])
    {
        int arr[] = { 23, 10, 20, 11, 12, 6, 7 };
        int n = arr.length;
 
        pancakeSort(arr, n);
 
        System.out.print("Sorted Array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}
 
// Contributed by sdeadityasharma


Output

Sorted Array: 6 7 10 11 12 20 23 

Time Complexity: O(n2)
Auxiliary space: O(1)

Please refer to the complete article on Pancake sorting for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads