Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Created January 19, 2024 14:11
Show Gist options
  • Save FlameWolf/db1397828a2a160b3211b933ec87077c to your computer and use it in GitHub Desktop.
Save FlameWolf/db1397828a2a160b3211b933ec87077c to your computer and use it in GitHub Desktop.
MergeSort implementation in JavaScript
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