Skip to content

Commit 1554d4b

Browse files
authoredSep 28, 2022
Create 969-pancake-sorting.js
1 parent 61068fc commit 1554d4b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
 

‎969-pancake-sorting.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number[]} arr
3+
* @return {number[]}
4+
*/
5+
const pancakeSort = function (arr) {
6+
const res = []
7+
let n = arr.length
8+
while(n) {
9+
const idx = indexOf(0, n - 1, n)
10+
if(idx === n - 1) {
11+
n--
12+
} else {
13+
flip(0, idx)
14+
flip(0, n - 1)
15+
res.push(idx + 1, n)
16+
n--
17+
}
18+
}
19+
return res
20+
21+
function flip(l, r) {
22+
while(l < r) {
23+
const tmp = arr[l]
24+
arr[l] = arr[r]
25+
arr[r] = tmp
26+
l++
27+
r--
28+
}
29+
}
30+
31+
function indexOf(start, end, target) {
32+
let res = -1
33+
for(let i = start; i <= end; i++) {
34+
if(arr[i]===target) {
35+
res = i
36+
break
37+
}
38+
}
39+
return res
40+
}
41+
}

0 commit comments

Comments
 (0)
Please sign in to comment.