Skip to content

Commit 2eacd84

Browse files
committed
Added pancake sorting
1 parent 1a41ce7 commit 2eacd84

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Other/PancakeSorting.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Given an an unsorted array, sort the given array.
3+
* You are allowed to do only following operation on array
4+
* flip(arr, i): Reverse array from 0 to i
5+
*
6+
* Tags: Sort
7+
*/
8+
class PancakeSorting {
9+
public static void main(String[] args) {
10+
PancakeSorting p = new PancakeSorting();
11+
int[] A = {23, 10, 20, 11, 12, 6, 7};
12+
p.pancakeSort(A);
13+
for (int n : A) System.out.print(n + ", ");
14+
}
15+
16+
/**
17+
* Find max from from start to end
18+
* If max is not at the end, filp it to first and flip it to end
19+
* Reduce array size by one
20+
* Stop till size reduced to 1
21+
*/
22+
public void pancakeSort(int[] A) {
23+
if (A == null || A.length <= 1) return;
24+
25+
for (int i = A.length; i > 1; i--) { // i is current size
26+
int mi = findMax(A, i);
27+
if (mi != i) {
28+
flip(A, mi);
29+
flip(A, i - 1);
30+
}
31+
}
32+
}
33+
34+
private void flip(int[] A, int i) {
35+
int temp, start = 0;
36+
while (start < i) {
37+
temp = A[start];
38+
A[start] = A[i];
39+
A[i] = temp;
40+
start++;
41+
i--;
42+
}
43+
}
44+
45+
private int findMax(int[] A, int size) {
46+
int mi = 0;
47+
for (int i = 0; i < size; i++) {
48+
if (A[i] > A[mi]) mi = i;
49+
}
50+
return mi;
51+
}
52+
}

0 commit comments

Comments
 (0)