Skip to content

Commit 37f1ae9

Browse files
authored
Merge pull request #1 from manojchawan/manojchawan-patch-1
PancakeSort.java
2 parents e47218d + 8c4c936 commit 37f1ae9

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

src/java/main/PancakeSort.java

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

0 commit comments

Comments
 (0)