Created
January 3, 2021 11:06
-
-
Save darkcris1/6a8a8d313b06514ade8709bc2cd73fc6 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm using 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
function sort(arrL, arrR) { | |
const newArray = [] | |
while (arrL.length && arrR.length) { | |
arrR[0] < arrL[0] | |
? newArray.push(arrR.shift()) | |
: newArray.push(arrL.shift()) | |
} | |
return newArray.concat(arrL, arrR) | |
} | |
function mergeSort(arr) { | |
if (arr.length <= 1) return arr | |
const divider = Math.ceil(arr.length / 2) | |
const arrLeft = arr.slice(0, divider) | |
const arrRight = arr.slice(divider) | |
return sort(mergeSort(arrLeft), mergeSort(arrRight)) | |
} | |
const arr = [7, 5, 1, 4, 9, 10, 2, 6, 8, 5, 5, 1000000, 33, 96, 98] | |
console.log(mergeSort(arr)) // [1, 2, 4, 5, 5, 5, 6, 7, 8, 9, 10, 33, 96, 98, 1000000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment