Skip to content

Instantly share code, notes, and snippets.

@dre4success
Created September 19, 2018 15:37
Show Gist options
  • Save dre4success/68e0a62254928b3c097aaece7c8e0337 to your computer and use it in GitHub Desktop.
Save dre4success/68e0a62254928b3c097aaece7c8e0337 to your computer and use it in GitHub Desktop.
A merge sort algorithm
// 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