Last active
January 19, 2016 08:54
-
-
Save ramsunvtech/2e4b87267ef9c05646a8 to your computer and use it in GitHub Desktop.
Merge Sort in Javascript
This file contains hidden or 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){ | |
var len = arr.length; | |
if(len <2) | |
return arr; | |
var mid = Math.floor(len/2), | |
left = arr.slice(0,mid), | |
right =arr.slice(mid); | |
//send left and right to the mergeSort to broke it down into pieces | |
//then merge those | |
return merge(mergeSort(left),mergeSort(right)); | |
} | |
function merge(left, right){ | |
var result = [], | |
lLen = left.length, | |
rLen = right.length, | |
l = 0, | |
r = 0; | |
while(l < lLen && r < rLen){ | |
if(left[l] < right[r]){ | |
result.push(left[l++]); | |
} | |
else{ | |
result.push(right[r++]); | |
} | |
} | |
//remaining part needs to be addred to the result | |
return result.concat(left.slice(l)).concat(right.slice(r)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment