Skip to content

Instantly share code, notes, and snippets.

@Millsky
Created May 19, 2019 01:31
Show Gist options
  • Save Millsky/a6fd397c4c7f28a7811bcc57dde7a851 to your computer and use it in GitHub Desktop.
Save Millsky/a6fd397c4c7f28a7811bcc57dde7a851 to your computer and use it in GitHub Desktop.
merge sort functional style
const merge = (a1,a2) => {
if (a1.length === 0) {
return a2;
}
if (a2.length === 0) {
return a1;
}
if (a1[0] <= a2[0]) {
return [
a1[0],
...merge(a1.slice(1,Infinity), a2)
];
} else if (a1[0] > a2[0]) {
return [
a2[0],
...merge(a1, a2.slice(1,Infinity))
];
}
}
const msort = (a) => {
if (a.length === 1) {
return a;
}
/* Calc middle */
const m = Math.round(a.length/2);
/* Get the first array half */
const firstHalf = a.slice(0,m);
/* Get the second array half */
const secondHalf = a.slice(m, Infinity);
/* Merge the two halves */
return merge(
/* Sort the first half */
msort(firstHalf),
/* Sort the second half */
msort(secondHalf)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment