Skip to content

Instantly share code, notes, and snippets.

@cefaijustin
Created November 10, 2018 18:42
Show Gist options
  • Save cefaijustin/c5c9790347019b91a9e5c45421338da2 to your computer and use it in GitHub Desktop.
Save cefaijustin/c5c9790347019b91a9e5c45421338da2 to your computer and use it in GitHub Desktop.
const mergeSort = (arr) => {
if (arr.length < 2) return arr;
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
const merge = (left, right) => {
const result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift())
} else {
result.push(right.shift())
}
}
return result.concat(left, right);
}
console.log(mergeSort([4, 2, 7, 1, 3, 5, 9]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment