-
Notifications
You must be signed in to change notification settings - Fork 243
/
PancakeSort.java
41 lines (37 loc) · 1.04 KB
/
PancakeSort.java
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
import java.util.Arrays;
public class PancakeSort {
public static void pancakeSort(int[] arr) {
int n = arr.length;
for (int i = n; i > 1; i--) {
int maxIndex = findMaxIndex(arr, i);
if (maxIndex != i - 1) {
flip(arr, maxIndex);
flip(arr, i - 1);
}
}
}
public static int findMaxIndex(int[] arr, int n) {
int maxIndex = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
public static void flip(int[] arr, int index) {
int start = 0;
while (start < index) {
int temp = arr[start];
arr[start] = arr[index];
arr[index] = temp;
start++;
index--;
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
pancakeSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}