Created
August 20, 2015 01:42
-
-
Save oddlyfunctional/585d385666407adf4130 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
function isEmpty(array) { | |
return array.length == 0; | |
} | |
function mergeSortedArrays(array1, array2) { | |
result = []; | |
// If there's anything in any of the arrays... | |
while (!isEmpty(array1) && !isEmpty(array2)) { | |
// ...we'll compare which one has the smallest next element... | |
if (array1[0] < array2[0]) { | |
// ...and add it to the end of result, removing it from the original array | |
result.push(array1.shift()); | |
} else { | |
result.push(array2.shift()); | |
} | |
} | |
// at the end, we simply finish inserting the rest of the elements of | |
// whatever array has still elements in it. This avoids missing elements | |
// when the arrays have different sizes. | |
while (!isEmpty(array1)) { | |
result.push(array1.shift()); | |
} | |
while (!isEmpty(array2)) { | |
result.push(array2.shift()); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment