Last active
August 29, 2015 13:57
-
-
Save dfsq/9850420 to your computer and use it in GitHub Desktop.
Merge two sorted arrays
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 mergeArrays(arr1, arr2) { | |
var out = [], | |
i = 0, | |
j = 0, | |
length = arr1.length; | |
while (arr2[j] < arr1[0]) { | |
out.push(arr2[j++]); | |
} | |
for (; i < length; i++) { | |
if (arr1[i] < arr2[j]) { | |
out.push(arr1[i]); | |
} | |
else { | |
while (arr2[j] < arr1[i]) { | |
out.push(arr2[j++]); | |
} | |
if (arr1[i] != arr2[j]) { | |
out.push(arr1[i]); | |
} | |
} | |
} | |
while (i < arr1.length) { | |
out.push(arr1[i++]); | |
} | |
while (j < arr2.length) { | |
out.push(arr2[j++]); | |
} | |
return out; | |
} | |
mergeArrays([2,3,4,5,9], [0,1,3,7]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment