Skip to content

Instantly share code, notes, and snippets.

@sghall
Last active November 27, 2017 06:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sghall/8586ff24aa28d03b1484309d00719e18 to your computer and use it in GitHub Desktop.
Save sghall/8586ff24aa28d03b1484309d00719e18 to your computer and use it in GitHub Desktop.
Merge Sort in JavaScript
const merge = (arrL, arrR) => {
const result = [];
let cursorL = 0;
let cursorR = 0;
while (cursorL < arrL.length && cursorR < arrR.length) {
if (arrL[cursorL] < arrR[cursorR]) {
result.push(arrL[cursorL++]);
} else {
result.push(arrR[cursorR++]);
}
}
return result.concat(arrL.slice(cursorL)).concat(arrR.slice(cursorR));
};
const mergeSort = (arr) => {
const len = arr.length;
if (len === 1) {
return arr;
}
const mid = Math.floor(len / 2);
return merge(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid, len)));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment