Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Last active April 7, 2019 21:19
Show Gist options
  • Select an option

  • Save 4skinSkywalker/a48226a096b9a8449b80c0496aa2afd2 to your computer and use it in GitHub Desktop.

Select an option

Save 4skinSkywalker/a48226a096b9a8449b80c0496aa2afd2 to your computer and use it in GitHub Desktop.
function merge(left, right) {
// REMEMBER THAT BOTH LEFT AND RIGHT ARE ALREADY ORDERED
let merged = [] // result array to return
let i = 0
let j = 0
while ( i < left.length && j < right.length ) {
// choose the smallest from the two
if ( left[i] <= right[j] ) {
merged.push( left[i] )
i++
} else {
merged.push( right[j] )
j++
}
}
// push all the left-over
while( left[i] ) {
merged.push( left[i] )
i++
}
while( right[j] ) {
merged.push( right[j] )
j++
}
return merged
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment