Skip to content

Instantly share code, notes, and snippets.

@langolf
Last active November 5, 2024 11:33
Show Gist options
  • Save langolf/f28db265b01a36fad039e54015508999 to your computer and use it in GitHub Desktop.
Save langolf/f28db265b01a36fad039e54015508999 to your computer and use it in GitHub Desktop.
sort
const mergeSort = (arr: number[]): number[] => {
if (arr.length < 2) {
return arr;
}
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);
const sortedLeft = mergeSort(left);
const sortedRight = mergeSort(right);
return merge(sortedLeft, sortedRight);
};
const merge = (left, right) => {
const result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result.concat(left, right);
};
const nums = [10, 5, 3, 8, 1, 4, 7, 9, 6, 2];
const ans = mergeSort(nums);
console.log(ans);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment