1
var pancakeSort = function (arr) {
2
let res = [];
3

4
for (let i = arr.length; i > 0; i--) {
5
//search the array for all values from 1 to n
6
let idx = arr.indexOf(i);
7
if (idx != i - 1) {
8
// if value is not present at its desired index
9
let pancake = arr.slice(0, idx + 1).reverse(); //flip the array with k=index of value i to put it in front of the array
10
res.push(idx + 1);
11
arr = arr.slice(idx + 1);
12
arr = pancake.concat(arr); //value i is now at index 0
13
pancake = arr.slice(0, i).reverse(); //flip the array with k = i-1 to put the value at its place
14
res.push(i);
15
arr = arr.slice(i);
16
arr = pancake.concat(arr); //now the array is sorted from i to n
17
}
18
}
19
return res;
20
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0