Created
May 15, 2022 14:03
-
-
Save fronterior/e57de56cac1290ff350e617e5ab29e27 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 mergeSort(array) { | |
const stack = [...array].map(n => [n]); | |
while (1) { | |
const nextStackItem = []; | |
const left = stack.shift(); | |
const right = stack.shift(); | |
let leftIndex = 0, rightIndex = 0; | |
if (left.length === array.length) { | |
return left; | |
} | |
while (leftIndex < left.length && rightIndex < right.length) { | |
if (left[leftIndex] < right[rightIndex]) { | |
nextStackItem.push(left[leftIndex]); | |
leftIndex++; | |
} else { | |
nextStackItem.push(right[rightIndex]); | |
rightIndex++; | |
} | |
} | |
nextStackItem.push(...left.slice(leftIndex), ...right.slice(rightIndex)); | |
stack.push(nextStackItem); | |
} | |
} | |
mergeSort(Array.from(Array(100), () => Math.floor(Math.random() * 100))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment