Skip to content

Instantly share code, notes, and snippets.

@tomgullo
Created September 4, 2013 17:31
Show Gist options
  • Save tomgullo/6440131 to your computer and use it in GitHub Desktop.
Save tomgullo/6440131 to your computer and use it in GitHub Desktop.
merge sort js
l = console.log
l("\n\nstart:")
function merge(left, right){
l("merge: l: " + left + ", r: " + right);
var result = [],
il = 0,
ir = 0;
while (il < left.length && ir < right.length){
if (left[il] < right[ir]){
result.push(left[il++]);
} else {
result.push(right[ir++]);
}
}
return result.concat(left.slice(il)).concat(right.slice(ir));
}
function mergeSort(items){
if (items.length < 2) {
// l("return: " + items);
return items;
}
var middle = Math.floor(items.length / 2),
left = items.slice(0, middle),
right = items.slice(middle);
l("mergeSort: left: " + left + ", right: " + right);
var params = merge(mergeSort(left), mergeSort(right));
l("\nafter merge: " + params);
return params;
}
l(mergeSort([3,10,2,5,22,6,9,20]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment