-
Notifications
You must be signed in to change notification settings - Fork 368
Expand file tree
/
Copy pathPanCakeSort.java
More file actions
47 lines (40 loc) · 1.18 KB
/
PanCakeSort.java
File metadata and controls
47 lines (40 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Arrays;
public class PanCakeSort {
public static void flip(int[] arr, int i) {
int start = 0;
while (start < i) {
int temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
start++;
i--;
}
}
public static int findMaxIndex(int[] arr, int n) {
int maxIndex = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
public static void pancakeSort(int[] arr) {
int n = arr.length;
for (int currSize = n; currSize > 1; currSize--) {
int maxIndex = findMaxIndex(arr, currSize);
if (maxIndex != currSize - 1) {
flip(arr, maxIndex);
flip(arr, currSize - 1);
}
}
}
public static void main(String[] args) {
int[] arr = { 6, 3, 9, 2, 5 };
System.out.print("Original array: ");
System.out.println(Arrays.toString(arr));
pancakeSort(arr);
System.out.print("Sorted array: ");
System.out.println(Arrays.toString(arr));
}
}