Skip to content

Instantly share code, notes, and snippets.

@ergomancer
Last active June 18, 2025 15:37
Show Gist options
  • Select an option

  • Save ergomancer/455907c17164e8481eba4dbdbae993d0 to your computer and use it in GitHub Desktop.

Select an option

Save ergomancer/455907c17164e8481eba4dbdbae993d0 to your computer and use it in GitHub Desktop.
A merge sort alogrithm in JS
const merge = function (arr1, arr2) {
let output = [];
let target;
while (true) {
if (arr1.length == 0 && arr2.length == 0) break;
else if (arr1.length == 0 && arr2.length != 0) target = arr2;
else if (arr1.length != 0 && arr2.length == 0) target = arr1;
else {
if (arr1[0] > arr2[0]) target = arr2;
else target = arr1;
}
output.push(target[0]);
target = target.splice(0, 1);
}
return output;
}
const mergeSort = function (arr) {
let output = []
if (arr.length == 1) {
output.push(arr[0]);
return output;
}
else {
let middle = Math.floor(arr.length/2);
let left = (arr.slice(0, middle));
let right = (arr.slice(middle));
let sortedLeft = mergeSort(left);
let sortedRight = mergeSort(right);
output = merge(sortedLeft, sortedRight);
return output;
}
}
module.exports=mergeSort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment