Last active
September 29, 2016 23:26
-
-
Save mitrakmt/17fcff1d43a12eee789cde10be50b1a4 to your computer and use it in GitHub Desktop.
Exploring merge sort in JavaScript.
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
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