Skip to content

Instantly share code, notes, and snippets.

@pherris
Created March 5, 2014 04:55
Show Gist options
  • Save pherris/9361458 to your computer and use it in GitHub Desktop.
Save pherris/9361458 to your computer and use it in GitHub Desktop.
MergeSort example in JavaScript
var MergeSorter = (function () {
var merge = function (arr1, arr2) {
var result = [];
while (arr1.length > 0 && arr2.length > 0) {
if (arr1[0] <= arr2[0]) {
result.push(arr1.shift());
} else {
result.push(arr2.shift());
}
}
while (arr1.length > 0) {
result.push(arr1.shift());
}
while (arr2.length > 0) {
result.push(arr2.shift());
}
return result;
}, iterations = 0;
return {
mergeSort: function (arr) {
iterations++;
if (arr. length < 2) {
return arr;
}
var splitPoint = Math.round(arr.length / 2),
arrOne = arr.slice(0, splitPoint),
arrTwo = arr.slice(splitPoint, arr.length);
//console.log(iterations);
return merge(this.mergeSort(arrOne), this.mergeSort(arrTwo));
}
};
}());
MergeSorter.mergeSort([4,5,2,4,2,-5,2,4,34,53,45,345,3,5,345,67,3,45,34,5]);
//[-5, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 34, 34, 45, 45, 53, 67, 345, 345]
MergeSorter.mergeSort(["andrew","kristina","john","greg"]);
//["andrew", "greg", "john", "kristina"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment