Created
January 19, 2024 14:11
-
-
Save FlameWolf/db1397828a2a160b3211b933ec87077c to your computer and use it in GitHub Desktop.
MergeSort implementation 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
function mergeSort(input) { | |
const merge = (left, right) => { | |
const merged = []; | |
while (left.length && right.length) { | |
if (left[0] < right[0]) { | |
merged.push(left.shift()); | |
} else { | |
merged.push(right.shift()); | |
} | |
} | |
return [...merged, ...left, ...right]; | |
}; | |
const sort = source => { | |
if (source.length === 1) { | |
return source; | |
} | |
const mid = Math.floor(source.length / 2); | |
const left = source.slice(0, mid); | |
const right = source.slice(mid); | |
return merge(sort(left), sort(right)); | |
}; | |
return sort(input); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment