×

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is:

Flip the arrays arr at index 0 to index j by using flipArr(arr, h).

Other sorting algorithms often aim to sort an array's elements using the fewest possible element comparisons. Therefore, using pancake sorting, we concentrate on arranging the array's items in a way that causes the fewest reversals.

The assignment is to sort the supplied array from an unsorted array. Only the following array operations are permitted.

flip(arr, s): Reverse array from 0 to s

Example 1:

Input: arr[] = { 24, 9, 19, 10, 11, 5, 8 }

Output: { 5, 8, 9, 10, 11, 19, 24}

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

Output: { 0, 0, 0, 1, 1 }

Pancakes Sorting Steps

The objective is to sort the series in as few reversals as feasible, in contrast to a standard sorting algorithm, which seeks to arrange with both the fewest comparisons possible.

The stages involved in sorting pancakes are as follows.

  • Start well with present size, which would be equal to s, then lower it by 1 if it is greater than 1. Let's say that the currSize is used to reflect the current size. Do the next step for every single currSize at this point.
  • Lookup of the index in the array arr[0... currSize - 1] where the largest element resides Let's say the index is "idx."
  • call flipArr(arr, idx)
  • call flipArr (arr, currSize - 1)

The implementation

Using the methods outlined above, the following code demonstrates how to achieve pancake sorting.

public class PancakeSortingDemo  
{  
// it is used Reverse the array as arr[0 ... h]   
public void flipArr(int arr[], int h)  
{  
int c, begin = 0;  
while (begin < h)  
{  
c = arr[begin];  
arr[begin] = arr[h];  
arr[j] = c;  
begin = begin + 1;  
h = h - 1;  
}  
}  
// Returning the element's 
// maximum index, which is included in the 
// array arr[0...a- 1].
public int findMax(int arr[], int a)  
{  
int index, h;  
for (index = 0, h = 0; h < a; ++h)  
{  
if (arr[h] > arr[index])  
{  
index = h;  
}  
}  
return index;  
}  
// The primary method uses flip operations to 
// sort the supplied array.
public int pancakeSorting(int arr[], int a)  
{  
// Change the current size with 1 
// starting with the full array and going through 
// each element one by one.
for (int curSize = s; curSize > 1; --curSize)  
{  
// Find the maximum element's 
// index in the array 
// arr[0..cur size-1].
int index = findMax(arr, curSize);  
// Adding the maximum element, 
// if it is not already there, 
// towards the end of the existing array.
if (index != curSize - 1)  
{  
// We must first transfer 
// the greatest item to the beginning in order 
// to relocate the last element.
flipArr(arr, index);  
// The current array is being reversed in 
// order to move a maximum number to the end.
flipArr(arr, curSize - 1);  
}  
}  
return 0;  
}  
// a practical way for showing the array arr[]
public void displayArray(int arr[], int a)  
{  
for (int h = 0; h < a; h++)  
{  
System.out.print(arr[h] + " ");  
}  
System.out.println("");  
}  
// It is the main method   
public static void main (String argvs[])  
{  
int arr[] = {35, 99, 209, 102, 113, 65, 37, 67, 909};  
int a = arr.length;  
  
// making an object of the PancakeSortingDemo class
PancakeSortingDemo sr = new PancakeSortingDemo();  
System.out.println("The input array is: ");  
obj.displayArray(arr, a);  
obj.pancakeSorting(arr, a);  
System.out.println(" \nThe array after sorting is: ");  
obj.displayArray(arr, a);  
}  
}  

Output:

The input array is:
35  99  209  102  113  65  37  67  909


The array after sorting is: 
35  37  67  99  102  113  209  909

Let us try to understand with the explanation of it briefly.

We have carried a similar work to selection sort. The array's current size has been decreased by 1 after the maximum element was placed at the end. The current size keeps becoming smaller until the entire array is sorted.


Related Topics

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.