Created
August 30, 2018 12:46
-
-
Save oliverbth05/082b495590833bcfbc91d974e1f1a895 to your computer and use it in GitHub Desktop.
Merge 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 merge(arr1, arr2) { | |
let i = 0; | |
let j = 0; | |
let merged = []; | |
let arr1Full = false; | |
let arr2Full = false; | |
while (arr1Full === false && arr2Full === false) { | |
if ( i === arr1.length) { | |
arr1Full = true; | |
} | |
if ( j === arr2.length) { | |
arr2Full = true; | |
} | |
if(arr1[i] < arr2[j]) { | |
merged.push(arr1[i]); | |
i ++ | |
} | |
else if (arr2[j] < arr1[i]) { | |
merged.push(arr2[j]); | |
j ++ | |
} | |
else if (arr2[j] === arr1[i]) { | |
merged.push(arr1[i]); | |
merged.push(arr2[j]); | |
i++ | |
j++ | |
} | |
} | |
//If one of the arrays has been fully iterated over, add the remaining elements of the other array | |
while (merged.length < arr1.length + arr2.length) { | |
if (arr1Full) { | |
for (var k = j; k < arr2.length; k ++) { | |
merged.push(arr2[k]) | |
} | |
} | |
if (arr2Full) { | |
for (var k = i; k < arr1.length; k ++) { | |
merged.push(arr1[k]) | |
} | |
} | |
} | |
return merged | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment