Java Program for Pancake sorting
Last Updated :
06 Nov, 2023
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*/
OutputSorted 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
OutputSorted 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!
Similar Reads
Java Program for Selection Sort The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.Algorithm for Selection SortImplementation of Selection Sort in Java is mentioned below:Step 1: Array arr with N sizeStep 2: Init
2 min read
Java Program for Insertion Sort Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. In this article, we will write the program on Insertion Sort in Java.Please refer complete article on Insertion Sort for more details! Algorithm of Insertion SortThe algorithm of Insertion Sort is men
2 min read
Java Program to Sort an ArrayList ArrayList is the class provided in the Collection framework. In Java, the collection framework is defined in java.util package. ArrayList is used to dynamically stores the elements. It is more flexible than an array because there is no size limit in ArrayList. ArrayList stores the data in an unorder
6 min read
Sort an Array in Java using Comparator A Comparator is an object that can be used to compare two objects and determine their order. We can use a Comparator to sort a list of objects in any order we can choose, not just in ascending order.Examples:Array(Ascending Order): Input: arr = (4, 2, 5, 1, 3) Output: [1, 2, 3, 4, 5] Array(Descendin
4 min read
Output of Java Programs | Set 33 (Collections) Prerequisite: Java - Collections 1. What is the output of following Java Program? Java import java.util.ArrayList; class Demo { public void show() { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(4); list.add(7); list.add(1); for (int number : list) { System.out.print(numbe
3 min read
Java Arrays Coding Practice Problems Arrays are a fundamental data structure in Java programming, enabling efficient storage, manipulation, and retrieval of elements. This collection of Java array practice problems covers essential operations, including array traversal, sorting, searching, matrix manipulations, and element-wise calcula
2 min read