Created
May 16, 2021 20:53
-
-
Save CarlaTeo/5baf67f5548d871d7382b28d8eb491ff to your computer and use it in GitHub Desktop.
[JS] Merge 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
function mergeSort(array) { | |
if(array.length <= 1) return array; | |
const half = Math.floor(array.length / 2); | |
const left = array.slice(0, half); | |
const right = array.slice(half); | |
const sortedLeft = mergeSort(left); | |
const sortedRight = mergeSort(right); | |
return merge(sortedLeft, sortedRight); | |
} | |
function merge(left, right) { | |
let l = 0; | |
let r = 0; | |
const sorted = []; | |
while(l < left.length && r < right.length) { | |
if(left[l] <= right[r]) { | |
sorted.push(left[l]); | |
l++; | |
} | |
else { | |
sorted.push(right[r]); | |
r++; | |
} | |
} | |
if(l < left.length) { | |
for(; l < left.length; l++) sorted.push(left[l]); | |
} | |
if(r < right.length) { | |
for(; r < right.length; r++) sorted.push(right[r]); | |
} | |
return sorted; | |
} | |
// -------------------------------------------------- Test --------------------------------------- // | |
const array = [8, 7, 1, 6, 9, 4, 8]; | |
console.log(mergeSort(array)); // [1, 4, 6, 7, 8, 8, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment