Skip to content

Instantly share code, notes, and snippets.

@juanigallo
Created September 8, 2017 13:45
Show Gist options
  • Save juanigallo/65468840d98156dcb0d26e273c6c6582 to your computer and use it in GitHub Desktop.
Save juanigallo/65468840d98156dcb0d26e273c6c6582 to your computer and use it in GitHub Desktop.
MergeSort implementation in JavaScript
function mergeSort (arr) {
if (arr.length < 2) {
return arr;
}
var mid = Math.floor(arr.length / 2);
var subLeft = mergeSort(arr.slice(0, mid));
var subRight = mergeSort(arr.slice(mid));
return merge(subLeft, subRight);
}
function merge (node1, node2) {
var result = [];
while (node1.length > 0 && node2.length > 0)
result.push(node1[0] < node2[0]? node1.shift() : node2.shift());
return result.concat(node1.length? node1 : node2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment