Skip to content

Instantly share code, notes, and snippets.

@dfsq
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfsq/9850420 to your computer and use it in GitHub Desktop.
Save dfsq/9850420 to your computer and use it in GitHub Desktop.
Merge two sorted arrays
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