×

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

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 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.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.