Last active
September 9, 2016 19:47
-
-
Save jmsevold/194f3ac6ccb80672841e0f8514555e72 to your computer and use it in GitHub Desktop.
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
// write a function that merges two unsorted arrays | |
function merge(leftArr,rightArr){ | |
let merged = []; | |
let i = 0; | |
let j = 0; | |
// while we are still inbounds for both arrays | |
while(i < leftArr.length && j < rightArr.length){ | |
if(leftArr[i] < rightArr[j]){ | |
merged.push(leftArr[i]); | |
i++; | |
}else if(rightArr[j] < leftArr[i]){ | |
merged.push(rightArr[j]); | |
j++; | |
} | |
} | |
// if either counter is out of bounds, the other array has the remaining numbers which can simply be appended | |
if( i < leftArr.length ){ | |
merged = merged.concat(leftArr.slice(i)); | |
} | |
else if ( j < rightArr.length){ | |
merged = merged.concat(rightArr.slice(j)); | |
} | |
console.log(merged); | |
} | |
merge([2,4,5],[1,3,7]); // [1,2,3,4,5,7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment