Created
August 29, 2020 09:05
-
-
Save RP-3/0f10eb0cf361726c595e807a269e3728 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} A | |
* @return {number[]} | |
*/ | |
// O(n**2) time. O(1) space. | |
// beats 95%! | |
var pancakeSort = function(A) { | |
const wc = []; | |
let end = A.length-1; | |
while(end > 0) { | |
const i = indexOfLargest(end); | |
if(i !== end){ | |
wc.push(i+1); | |
flip(i); | |
wc.push(end+1); | |
flip(end); | |
} | |
end--; | |
}; | |
return wc; | |
// private helpers | |
function indexOfLargest(end){ | |
let [largest, index] = [A[0], 0]; | |
for(let i=0; i<=end; i++){ | |
if(A[i] > largest) [largest, index] = [A[i], i]; | |
} | |
return index; | |
} | |
function flip(index){ | |
let [l, r] = [0, index]; | |
while(l < r){ | |
[A[l], A[r]] = [A[r], A[l]]; | |
l++; r--; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment