Last active
September 19, 2020 23:29
-
-
Save hylobates-lar/200e3e280e39c04fe09bcc7c55974d56 to your computer and use it in GitHub Desktop.
Ratatouille merge sort
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
let zucchiniSlices = [20, 11, 25, 3, 14, 5,...] | |
const merge = (arr1, arr2) => { | |
let sorted = []; | |
while (arr1.length && arr2.length) { | |
if (arr1[0] < arr2[0]) { | |
sorted.push(arr1.shift()); | |
} else { | |
sorted.push(arr2.shift()); | |
} | |
}; | |
return sorted.concat(arr1.slice().concat(arr2.slice())); | |
}; | |
const mergeSortByBestSlices = veggieSlices => { | |
if (veggieSlices.length <= 1) return veggieSlices; | |
let mid = Math.floor(veggieSlices.length / 2), | |
left = mergeSortByBestSlices(veggieSlices.slice(0, mid)), | |
right = mergeSortByBestSlices(veggieSlices.slice(mid)); | |
return merge(left, right); | |
}; | |
mergeSortByBestSlices(zucchiniSlices) // [1, 2, 3, 4, 5, 6,...] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment