Skip to content

Instantly share code, notes, and snippets.

@radicalsauce
Last active Oct 7, 2015
Embed
What would you like to do?
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