Last active
November 5, 2024 11:33
-
-
Save langolf/f28db265b01a36fad039e54015508999 to your computer and use it in GitHub Desktop.
sort
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
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