Created
March 12, 2021 01:34
-
-
Save ulises-codes/58e31c76002e5bea37fbee3e789d25b1 to your computer and use it in GitHub Desktop.
A simple implementation of a merge sort algorithm.
This file contains 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(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