Skip to content

Instantly share code, notes, and snippets.

@hylobates-lar
Last active September 19, 2020 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hylobates-lar/200e3e280e39c04fe09bcc7c55974d56 to your computer and use it in GitHub Desktop.
Save hylobates-lar/200e3e280e39c04fe09bcc7c55974d56 to your computer and use it in GitHub Desktop.
Ratatouille merge sort
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