Last active
November 27, 2017 06:58
-
-
Save sghall/8586ff24aa28d03b1484309d00719e18 to your computer and use it in GitHub Desktop.
Merge Sort in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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