Created
September 19, 2018 15:37
-
-
Save dre4success/68e0a62254928b3c097aaece7c8e0337 to your computer and use it in GitHub Desktop.
A merge sort algorithm
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
// a function that takes two arrays and merge them | |
function merge(arr1, arr2){ | |
let i = 0 | |
let j = 0 | |
let results = [] | |
while (i < arr1.length && j < arr2.length) { | |
if(arr2[j] > arr1[i]) { | |
results.push(arr1[i]) | |
i++ | |
} else { | |
results.push(arr2[j]) | |
j++ | |
} | |
} | |
while(i < arr1.length) { | |
results.push(arr1[i]) | |
i++ | |
} | |
while(j < arr2.length) { | |
results.push(arr2[j]) | |
j++ | |
} | |
return results | |
} | |
// breaks an array in to subarrays and passes them to the merge function which returns a sorted array | |
function mergeSort(arr) { | |
if(arr.length <= 1) return arr | |
let mid = Math.floor(arr.length / 2) | |
let left = mergeSort(arr.slice(0, mid)) | |
let right = mergeSort(arr.slice(mid)) | |
return merge(left, right) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment