Skip to content

Instantly share code, notes, and snippets.

@Dornhoth
Last active July 2, 2020 19:49
Show Gist options
  • Select an option

  • Save Dornhoth/8985ff4d3f9cab3eb8e421fc2ac690df to your computer and use it in GitHub Desktop.

Select an option

Save Dornhoth/8985ff4d3f9cab3eb8e421fc2ac690df to your computer and use it in GitHub Desktop.
function merge(left, right) {
const result = [];
while (left.length > 0 && right.length > 0) {
if (left[0] <= right[0]) {
result.push(left[0]);
left = left.slice(1);
} else {
result.push(right[0]);
right = right.slice(1);
}
}
while (left.length > 0) {
result.push(left[0]);
left = left.slice(1);
}
while (right.length > 0) {
result.push(right[0]);
right = right.slice(1);
}
return result;
}
function mergeSort(array) {
if (array.length <= 1) {
return array;
}
let left = [];
let right = [];
for (let i = 0; i < array.length; i += 1) {
if (i < array.length / 2) {
left.push(array[i]);
} else {
right.push(array[i]);
}
}
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment