CodeX
Published in

CodeX

CODEX

Merge Sort: Broken Down Line by Line

function merge(arr1, arr2){
let result = []
let i = 0
let j = 0

while( i < arr1.length && j < arr2.length){
if(arr2[j] > arr1[i]){
result.push(arr1[i])
i++
} else {
result.push(arr2[j])
j++
}
}

while(i < arr1.length){
result.push(arr1[i])
i++
}
while(j < arr2.length){
result.push(arr2[j])
j++
}

return result
}
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)

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ryan Flynn

Full-Stack Engineer with a background in Javascript, React.js, React Native, Redux, Ruby, and Ruby on Rails.