forked from atyant-yadav/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortArray.js
More file actions
31 lines (28 loc) · 727 Bytes
/
MergeSortArray.js
File metadata and controls
31 lines (28 loc) · 727 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function mergeSortedArrays(array1, array2){
const mergedArray = [];
let array1Item = array1[0];
let array2Item = array2[0];
let i = 1;
let j = 1;
//We should actually move these 2 if statements to line 2 so that we do the checks before we do assignments in line 3 and 4!
if(array1.length === 0) {
return array2;
}
if(array2.length === 0) {
return array1;
}
while (array1Item || array2Item){
if(array2Item === undefined || array1Item < array2Item){
mergedArray.push(array1Item);
array1Item = array1[i];
i++;
}
else {
mergedArray.push(array2Item);
array2Item = array2[j];
j++;
}
}
return mergedArray;
}
mergeSortedArrays([0,3,4,31], [3,4,6,30]);