Skip to content

Instantly share code, notes, and snippets.

@ncou
Forked from jasondscott/mergeSort.js
Created August 23, 2016 09:53
Show Gist options
  • Save ncou/f76ed8c793e7a2c821d6b8dd79e08b76 to your computer and use it in GitHub Desktop.
Save ncou/f76ed8c793e7a2c821d6b8dd79e08b76 to your computer and use it in GitHub Desktop.
JavaScript Merge Sort
//Merge Sort
Array.prototype.mergeSort = function() {
var thiz = this;
if (this.length <= 1) {
return this;
}
//split left and right
var left = [], right = [];
var mid = Math.floor(thiz.length/2);
right = thiz.slice(mid);
left = thiz.slice(0, mid);
return merge(left.mergeSort(), right.mergeSort());
function merge(a, b) {
var m = [];
while (a.length && b.length) {
if (a[0] < b[0]) {
m.push(a.shift());
} else {
m.push(b.shift());
}
}
if (a.length > 0) {
m = m.concat(a);
}
if (b.length > 0) {
m = m.concat(b);
}
return m;
}
};
var a = [123,12,3,1534,75,1,99];
console.log(a.mergeSort());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment