Skip to content

Instantly share code, notes, and snippets.

@fronterior
Created May 15, 2022 14:03
Show Gist options
  • Save fronterior/e57de56cac1290ff350e617e5ab29e27 to your computer and use it in GitHub Desktop.
Save fronterior/e57de56cac1290ff350e617e5ab29e27 to your computer and use it in GitHub Desktop.
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