Skip to content

Instantly share code, notes, and snippets.

@eengineergz
Created February 27, 2021 04:59
Show Gist options
  • Save eengineergz/18fbb7edc9f5c4820ccfcecacf3c5e48 to your computer and use it in GitHub Desktop.
Save eengineergz/18fbb7edc9f5c4820ccfcecacf3c5e48 to your computer and use it in GitHub Desktop.
function merge(leftArray, rightArray) {
const sorted = [];
while (letArray.length > 0 && rightArray.length > 0) {
const leftItem = leftArray[0];
const rightItem = rightArray[0];
if (leftItem > rightItem) {
sorted.push(rightItem);
rightArray.shift();
} else {
sorted.push(leftItem);
leftArray.shift();
}
}
while (leftArray.length !== 0) {
const value = leftArray.shift();
sorted.push(value);
}
while (rightArray.length !== 0) {
const value = rightArray.shift();
sorted.push(value);
}
return sorted;
}
function mergeSort(array) {
const length = array.length;
if (length === 1) {
return array;
}
const middleIndex = Math.ceil(length / 2);
const leftArray = array.slice(0, middleIndex);
const rightArray = array.slice(middleIndex, length);
leftArray = mergeSort(leftArray);
rightArray = mergeSort(rightArray);
return merge(leftArray, rightArray);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment