Created
October 4, 2015 18:40
-
-
Save nathanboktae/dc3072cb19aec6119ceb to your computer and use it in GitHub Desktop.
JavaScript merge sort in 30 lines that's only 10% slower than native in V8 - http://jsperf.com/merge-sort/3
This file contains hidden or 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
if (!Array.prototype.mergeSort) { | |
Array.prototype.mergeSort = function(predicate) { | |
if (this.length < 2) return this | |
var middle = Math.round(this.length / 2), | |
left = this.slice(0, middle).mergeSort(predicate), | |
right = this.slice(middle, this.length).mergeSort(predicate), | |
merged = [], leftCursor = 0, rightCursor = 0, | |
predicate = predicate || function(a, b) { return a <= b ? -1 : 1 } | |
while (leftCursor < left.length && rightCursor < right.length) { | |
if (predicate(left[leftCursor], right[rightCursor]) <= 0) { | |
merged.push(left[leftCursor]) | |
leftCursor++ | |
} else { | |
merged.push(right[rightCursor]) | |
rightCursor++ | |
} | |
} | |
if (leftCursor < left.length) { | |
merged.splice.apply(merged, left.slice(leftCursor)) | |
} | |
if (rightCursor < right.length) { | |
merged.splice.apply(merged, right.slice(rightCursor)) | |
} | |
return merged | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment