Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created February 7, 2017 22:46
Show Gist options
  • Save jasonwaters/374e31fe074e2f159cddf6a70b075df1 to your computer and use it in GitHub Desktop.
Save jasonwaters/374e31fe074e2f159cddf6a70b075df1 to your computer and use it in GitHub Desktop.
Merge Sort
function merge(arrA, arrB) {
let idxA=0, idxB=0, result=[];
while(idxA < arrA.length || idxB < arrB.length) {
if(idxB === arrB.length || arrA[idxA] <= arrB[idxB]) {
result.push(arrA[idxA]);
idxA++;
}else if(idxA === arrA.length || arrB[idxB] <= arrA[idxA]) {
result.push(arrB[idxB]);
idxB++;
}
}
return result;
}
function mergeSort(array) {
let len = array.length;
let middle = parseInt(len / 2);
let left = array.slice(0, middle);
let right = array.slice(middle, len);
left = left.length > 1 ? mergeSort(left) : left;
right = right.length > 1 ? mergeSort(right) : right;
return merge(left, right);
}
console.log(mergeSort([9, 6, -7, 4, 9, 4, 6, 9, 7, -7]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment