Skip to content

Instantly share code, notes, and snippets.

@cefaijustin
Created November 10, 2018 01:36
Show Gist options
  • Save cefaijustin/9132ba54631e14f36ec594446c7c2cd3 to your computer and use it in GitHub Desktop.
Save cefaijustin/9132ba54631e14f36ec594446c7c2cd3 to your computer and use it in GitHub Desktop.
mergeSort = (arr) => {
if (arr.length < 2) return arr;
var middle = Math.floor(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
merge = (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;
}
console.log(mergeSort([3, 1, 6, 2, 7]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment