Created
July 31, 2021 20:34
-
-
Save wescosta/005210a583261408697c7acbd90cf641 to your computer and use it in GitHub Desktop.
Merge sort JS implementation
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(nums){ | |
if (nums.length === 1) return nums; | |
const half = Math.floor(nums.length / 2); | |
const left = mergeSort(nums.slice(0, half)); | |
const right = mergeSort(nums.slice(half)); | |
return merge(left, right); | |
} | |
function merge(left, right){ | |
let result = []; | |
let l = 0, r = 0; | |
while (l < left.length && r < right.length){ | |
if (left[l] < right[r]){ | |
result.push(left[l]); | |
l++; | |
} else { | |
result.push(right[r]); | |
r++; | |
} | |
} | |
if (l < left.length){ | |
result = result.concat(left.slice(l)); | |
} else if (r < right.length) { | |
result = result.concat(right.slice(r)); | |
} | |
return result; | |
} | |
const nums = Array(10).fill(100).map(n => parseInt(n * Math.random())); | |
console.log(mergeSort(nums)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment