969. Pancake Sorting
class Solution {
List<Integer> result = new LinkedList<>();
public List<Integer> pancakeSort(int[] arr) {
recursion(arr, arr.length-1);
return result;
}
private void recursion(int[] arr, int end){
if(end==0){
return;
}
int index = max(arr, end);
if(index!=end){
result.add(index+1);
result.add(end+1);
flip(arr, index);
flip(arr, end);
}
recursion(arr, end-1);
}
// return the index of the largest num from [0, end];
private int max(int[] arr, int end){
int maxIndex = 0;
for(int i=1; i<=end; i++){
maxIndex = arr[i]>arr[maxIndex] ? i:maxIndex;
}
return maxIndex;
}
private void flip(int[] arr, int end){
int start=0;
while(start<end){
int temp = arr[end];
arr[end]=arr[start];
arr[start]=temp;
start++;
end--;
}
}
}
Last updated
Was this helpful?