Last active
October 7, 2015 01:06
-
-
Save radicalsauce/497baaaf2354fd71d688 to your computer and use it in GitHub Desktop.
Javascript MergeSort
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
// A simple JS mergesort, per Wikipedia's pseudocode | |
// http://en.wikipedia.org/wiki/Mergesort | |
// by K.R. Hale | |
var mergeSort = function(array) { | |
//base case | |
if (array.length <= 1) return array; | |
//recursive case | |
var middle = Math.floor(array.length / 2); | |
var left = array.slice(0, middle); | |
var right = array.slice(middle, array.length); | |
return merge(mergeSort(left), mergeSort(right)); | |
}; | |
var merge = function(left, right) { | |
var result = []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) result.push(left.shift()); | |
else result.push(right.shift()); | |
} | |
while (left.length) result.push(left.shift()); | |
while (right.length) result.push(right.shift()); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment