Last active
June 7, 2020 03:16
-
-
Save andresabello/6d359ee4bc4236c76fe977fffa728c01 to your computer and use it in GitHub Desktop.
merge-sort algorithm using Javascript
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 numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]; | |
function mergeSort(array) { | |
if (array.length === 1) { | |
return array | |
} | |
let half = array.length / 2 | |
let left = array.slice(0, half) | |
let right = array.slice(half) | |
return merge( | |
mergeSort(left), | |
mergeSort(right) | |
) | |
} | |
function merge(left, right) { | |
let result = [] | |
let leftIndex = 0 | |
let rightIndex = 0 | |
while(leftIndex < left.length && rightIndex < right.length) { | |
if (left[leftIndex] < right[rightIndex]) { | |
result.push(left[leftIndex]) | |
leftIndex++ | |
}else { | |
result.push(right[rightIndex]) | |
rightIndex++ | |
} | |
} | |
return result.concat(left.slice(leftIndex), right.slice(rightIndex)) | |
} | |
mergeSort(numbers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment