Skip to content

Instantly share code, notes, and snippets.

@tjeastmond
Created May 23, 2019 05:59
Show Gist options
  • Save tjeastmond/678397320c49403e720666c8411399d0 to your computer and use it in GitHub Desktop.
Save tjeastmond/678397320c49403e720666c8411399d0 to your computer and use it in GitHub Desktop.
/**
* Simple mergesort exercise
*/
const mergeSort = unsortedArray => {
if (unsortedArray.length <= 1) return unsortedArray;
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(mergeSort(left), mergeSort(right));
};
const merge = (left, right) => {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return [
...resultArray,
...left.slice(leftIndex),
...right.slice([rightIndex])
];
};
const array = [10, -1, 2, 5, 0, 6, 4, -5];
const array2 = ["TJ", "Melissa", "Figs", "Autumn", "Mooch"];
console.log("mergeSort(array): ", mergeSort(array));
// console.log("mergeSort(array2): ", mergeSort(array2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment