-
-
Save eengineergz/18fbb7edc9f5c4820ccfcecacf3c5e48 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
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