Skip to content

Instantly share code, notes, and snippets.

@radicalsauce
Last active October 7, 2015 01:06
Show Gist options
  • Save radicalsauce/497baaaf2354fd71d688 to your computer and use it in GitHub Desktop.
Save radicalsauce/497baaaf2354fd71d688 to your computer and use it in GitHub Desktop.
Javascript MergeSort
// 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