Skip to content

Instantly share code, notes, and snippets.

@kaz-a
Last active September 2, 2021 15:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaz-a/33dd72906f39c1a7959b8cf45d1e52e9 to your computer and use it in GitHub Desktop.
Save kaz-a/33dd72906f39c1a7959b8cf45d1e52e9 to your computer and use it in GitHub Desktop.
Pancake sort algorithm
// swap helper function
const swap = (arr, start, end) => {
let temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
// flip helper function using swap
const flip = (arr, k) => {
let start = 0;
let end = k;
while (start < end) {
swap(arr, start, end);
start++;
end--;
}
}
const pancakeSort = arr => {
for (let i=arr.length-1; i>=0; i--) {
let max = -Infinity;
let maxIndex = i;
let prefix = arr.slice(0, i + 1);
// 1. find the index of the largest size in unsorted arr
for (let j = 0; j<prefix.length; j++) {
if (prefix[j] > max) {
max = prefix[j];
maxIndex = j;
}
}
// 2. flip the largest element to index 0
flip(arr, maxIndex);
// 3. then flip the largest element to the sorted index
flip(arr, i);
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment