-
-
Save ncou/f76ed8c793e7a2c821d6b8dd79e08b76 to your computer and use it in GitHub Desktop.
JavaScript Merge Sort
This file contains 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
//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