Java Program for Pancake sorting

Java 8Server Side ProgrammingProgramming

Pancake sorting is a sorting technique that resembles selection sort, i.e. sorting the largest element first thereby reducing the size of the array and eventually sorting all the elements. In pancake sorting, the idea is to sort the array elements by making the least number of reversals.

Following is an example for Pancake sorting in Java −

Example

 Live Demo

import java.io.*;
public class pancake_sorting {
   static void flip_array(int my_arr[], int i) {
      int temp, beg = 0;
      while (beg < i) {
         temp = my_arr[beg];
         my_arr[beg] = my_arr[i];
         my_arr[i] = temp;
         beg++;
         i--;
      }
   }
   static int find_index(int my_arr[], int n) {
      int max_ele, i;
      for (max_ele = 0, i = 0; i < n; ++i)
         if (my_arr[i] > my_arr[max_ele])
         max_ele = i;
      return max_ele;
   }
   static int pancake_sort(int my_arr[], int n) {
      for (int curr_size = n; curr_size > 1; --curr_size) {
         int max_ele = find_index(my_arr, curr_size);
         if (max_ele != curr_size - 1) {
            flip_array(my_arr, max_ele);
            flip_array(my_arr, curr_size - 1);
         }
      }
      return 0;
   }
   public static void main(String[] args) {
      int my_arr[] = { 67, 43, 89, 11, 23, 0, 98, 102, 4 };
      int arr_len = my_arr.length;
      pancake_sort(my_arr, arr_len);
      System.out.println("The sorted array is : ");
      for (int i = 0; i < arr_len; i++)
      System.out.print(my_arr[i] + " ");
      System.out.println("");
   }
}

Output

The sorted array is :
0 4 11 23 43 67 89 98 102

Explanation

When an unsorted array is defined in the main function, the ‘pancake_sort’ takes this array as a parameter, and sorts the array. Only one operation is done on the array which is a flip- ‘flip_array’.

In this function, the array is reversed from element 0 to a specific element in the array. The goal is to sort the array with the help of least number of reversals. This is similar to selection sort where the largest element is placed at the end one by one to reduce size of array by 1. The array is begun to sort, and the largest element is placed in the last position. This way, the size of the array comes down by one. Find the maximum element in the array and its index. Assign a variable to the index. Now the ‘flip_array’ function is called. The same operation is performed on the array elements until all elements are sorted.

raja
Published on 14-Sep-2020 08:18:19
Advertisements