Skip to content

Instantly share code, notes, and snippets.

@ulises-codes
Created March 12, 2021 01:34
Show Gist options
  • Save ulises-codes/58e31c76002e5bea37fbee3e789d25b1 to your computer and use it in GitHub Desktop.
Save ulises-codes/58e31c76002e5bea37fbee3e789d25b1 to your computer and use it in GitHub Desktop.
A simple implementation of a merge sort algorithm.
function mergeSort(arr: number[]): number[] {
const length = arr.length;
if (length === 1) return arr;
const middle = Math.floor(length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle, length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left: number[], right: number[]): number[] {
const sorted: number[] = [];
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) {
sorted.push(left[0]);
left.shift();
} else {
sorted.push(right[0]);
right.shift();
}
}
return sorted.concat(left);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment