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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read