Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created August 29, 2020 09:05
Show Gist options
  • Save RP-3/0f10eb0cf361726c595e807a269e3728 to your computer and use it in GitHub Desktop.
Save RP-3/0f10eb0cf361726c595e807a269e3728 to your computer and use it in GitHub Desktop.
/**
* @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