Created
December 27, 2019 00:42
-
-
Save srph/e39234a3c77b69c3c3faa2639c4089ae to your computer and use it in GitHub Desktop.
JS: Merge sort - programming exercise
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 array = [38, 27, 24, 56, 12, 32, 16, 11, 15, 25, 29]; | |
console.log(mergeSort(array)); |
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 middle = Math.floor(array.length / 2); | |
const left = array.slice(0, middle); | |
const right = array.slice(middle); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
function merge(left, right) { | |
const 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)]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment