Last active
October 31, 2018 20:59
-
-
Save Tellisense/f2302decc4921582663ba7e587ae96b4 to your computer and use it in GitHub Desktop.
Merge Sort JavaScript
This file contains hidden or 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 mergeSort(arr) { | |
if (arr.length === 1) { | |
return arr; | |
} | |
const center = Math.floor(arr.length / 2); | |
const left = arr.slice(0, center); | |
const right = arr.slice(center); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
function merge(left, right) { | |
const results = []; | |
while (left.length && right.length) { | |
if (left[0] < right[0]) { | |
results.push(left.shift()); | |
} else { | |
results.push(right.shift()); | |
} | |
} | |
return [...results, ...left, ...right] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment