Skip to content

Instantly share code, notes, and snippets.

@nathanboktae
Created October 4, 2015 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanboktae/dc3072cb19aec6119ceb to your computer and use it in GitHub Desktop.
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
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