Skip to content

Instantly share code, notes, and snippets.

@srph
Created January 10, 2022 00:56
Show Gist options
  • Save srph/7d25ee31824b6296b94e008e50bd1d77 to your computer and use it in GitHub Desktop.
Save srph/7d25ee31824b6296b94e008e50bd1d77 to your computer and use it in GitHub Desktop.
JS: Merge sort (post-holidays exercise)
const merge = (left: number[], right: number[]): number[] => {
let result = []
let lindex = 0
let rindex = 0
while (lindex < left.length && rindex < right.length) {
if (left[lindex] < right[rindex]) {
result.push(left[lindex])
lindex++
} else {
result.push(right[rindex])
rindex++
}
}
return [...result, ...left.slice(lindex), ...right.slice(rindex)]
}
const mergeSort = (arr: number[]): number[] => {
if (arr.length <= 1) {
return arr
}
const middle = Math.floor(arr.length / 2)
const left = arr.slice(0, middle)
const right = arr.slice(middle)
return merge(mergeSort(left), mergeSort(right))
}
const random = (min: number, max: number) => {
return Math.floor(Math.random() * (max - min) + min)
}
const numbers = Array.from({ length: 100 }).map(() => random(0, 500))
console.log(mergeSort(numbers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment