Last active
September 2, 2021 15:32
-
-
Save kaz-a/33dd72906f39c1a7959b8cf45d1e52e9 to your computer and use it in GitHub Desktop.
Pancake sort algorithm
This file contains 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
// 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