Created
May 23, 2019 05:59
-
-
Save tjeastmond/678397320c49403e720666c8411399d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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