Skip to content

Instantly share code, notes, and snippets.

@berlysia
Last active June 6, 2016 16:45
Show Gist options
  • Save berlysia/c2cb66e242aba116e24b0033a52be859 to your computer and use it in GitHub Desktop.
Save berlysia/c2cb66e242aba116e24b0033a52be859 to your computer and use it in GitHub Desktop.
function mergeSort(array) {
if(array.length <= 1) {
return array;
}
const mid = array.length / 2 | 0;
const left = mergeSort(array.slice(0, mid));
const right = mergeSort(array.slice(mid));
return merge(left, right);
};
function merge(left, right) {
const merged = [];
while(left.length && right.length) {
if(left[0] < right[0]) {
merged.push(left.shift());
} else {
merged.push(right.shift());
}
}
const rem = left.length ? left : right;
merged.push(...rem);
return merged;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment