-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPancake Sorting.java
More file actions
59 lines (46 loc) · 1.23 KB
/
Pancake Sorting.java
File metadata and controls
59 lines (46 loc) · 1.23 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
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public List<Integer> pancakeSort(int[] arr) {
//I used pancake sorting
ArrayList<Integer> list_of_k = new ArrayList<>();
int j = arr.length-1;
while(j >= 0)
{
//find max
int max = findMax(arr, 0, j);
//reverse arr upto max
reverse(arr, 0, max);
//add the k values
list_of_k.add(max+1);
//reverse arr upto j
reverse(arr, 0, j);
//add the k values
list_of_k.add(j+1);
//decrement
j--;
}
//return result
return list_of_k;
}
public int findMax(int[] arr, int i, int j)
{
int max = i;
for(int k = i+1; k <= j; k++)
{
if(arr[max] < arr[k])
max = k;
}
return max;
}
public void reverse(int[] arr, int i, int j)
{
int p1 = i, p2 = j;
while(p1 < p2)
{
int temp = arr[p1];
arr[p1] = arr[p2];
arr[p2] = temp;
p1++;
p2--;
}
}
}