1
+
2
+ // Java program to
3
+ // sort array using
4
+ // pancake sort
5
+ import java .io .*;
6
+
7
+ class PancakeSort {
8
+
9
+ /* Reverses arr[0..i] */
10
+ static void flip (int arr [], int i )
11
+ {
12
+ int temp , start = 0 ;
13
+ while (start < i )
14
+ {
15
+ temp = arr [start ];
16
+ arr [start ] = arr [i ];
17
+ arr [i ] = temp ;
18
+ start ++;
19
+ i --;
20
+ }
21
+ }
22
+
23
+ // Returns index of the
24
+ // maximum element in
25
+ // arr[0..n-1]
26
+ static int findMax (int arr [], int n )
27
+ {
28
+ int mi , i ;
29
+ for (mi = 0 , i = 0 ; i < n ; ++i )
30
+ if (arr [i ] > arr [mi ])
31
+ mi = i ;
32
+ return mi ;
33
+ }
34
+
35
+ // The main function that
36
+ // sorts given array using
37
+ // flip operations
38
+ static int pancakeSort (int arr [], int n )
39
+ {
40
+ // Start from the complete
41
+ // array and one by one
42
+ // reduce current size by one
43
+ for (int curr_size = n ; curr_size > 1 ; --curr_size )
44
+ {
45
+ // Find index of the
46
+ // maximum element in
47
+ // arr[0..curr_size-1]
48
+ int mi = findMax (arr , curr_size );
49
+
50
+ // Move the maximum element
51
+ // to end of current array
52
+ // if it's not already at
53
+ // the end
54
+ if (mi != curr_size -1 )
55
+ {
56
+ // To move at the end,
57
+ // first move maximum
58
+ // number to beginning
59
+ flip (arr , mi );
60
+
61
+ // Now move the maximum
62
+ // number to end by
63
+ // reversing current array
64
+ flip (arr , curr_size -1 );
65
+ }
66
+ }
67
+ return 0 ;
68
+ }
69
+
70
+ /* Utility function to print array arr[] */
71
+ static void printArray (int arr [], int arr_size )
72
+ {
73
+ for (int i = 0 ; i < arr_size ; i ++)
74
+ System .out .print (arr [i ] + " " );
75
+ System .out .println ("" );
76
+ }
77
+
78
+ /* Driver function to check for above functions*/
79
+ public static void main (String [] args )
80
+ {
81
+ int arr [] = {23 , 10 , 20 , 11 , 12 , 6 , 7 };
82
+ int n = arr .length ;
83
+
84
+ pancakeSort (arr , n );
85
+
86
+ System .out .println ("Sorted Array: " );
87
+ printArray (arr , n );
88
+ }
89
+ }
0 commit comments