Pancake Sorting in Java

In this section, we will learn about pancake sorting in Java. In pancake sorting, one has to sort the array by performing only one operation, and that operation is:

flipArr(arr, j): Reverse the array arr from index 0 to j.

Generally, in other sorting algorithms, the attempt is to sort the elements of an array with minimum comparisons of elements. However, in pancake sorting, we focus on sorting the elements of the array with the minimum reversals.

Steps Involved in Pancake Sorting

The following are the steps involved in pancake sorting.

  • Begin from the current size, which is equal to s and then reduce the current size by 1 while it is more than 1. Suppose the current size is represented by the currSize. Now, do the following for each and every currSize.
    • Search of the index where the maximum element sits in the arr[0… currSize - 1]. Suppose that index be 'idx'
    • Invoke flipArr(arr, idx)
    • Invoke flipArr(arr, currSize - 1)

Implementation

The following code shows the implementation of pancake sorting using the steps defined above.

FileName: PancakeSortingExample.java

Output:

Input Array is: 
23 100 210 101 112 66 27 67 809 

After sorting the array is: 
23 27 66 67 100 101 112 210 809

Explanation:

We have done something similar to Selection Sort. We put the maximum element at the last of the array, and then we have reduced the current size of the array by 1. The reduction of the current size continues till the whole array gets sorted.






Latest Courses