Skip to content

Instantly share code, notes, and snippets.

@ramsunvtech
Last active January 19, 2016 08:54
Show Gist options
  • Save ramsunvtech/2e4b87267ef9c05646a8 to your computer and use it in GitHub Desktop.
Save ramsunvtech/2e4b87267ef9c05646a8 to your computer and use it in GitHub Desktop.
Merge Sort in Javascript
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