-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeThreeSortedArrays.cpp
72 lines (71 loc) · 1.4 KB
/
mergeThreeSortedArrays.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Function to merge three sorted arrays
// A, B, and C: input sorted arrays
vector<int> mergeThree(vector<int>& A, vector<int>& B, vector<int>& C)
{
int l,m,n,i,j,k;
l=A.size();i=0;
m=B.size();j=0;
n=C.size();k=0;
vector<int> res;
int temp;
//taking three arrays at a time
while(i<l && j<m && k<n){
temp=min(min(A[i],B[j]),C[k]);
res.push_back(temp);
if(temp==A[i])
i++;
else if(temp==B[j])
j++;
else
k++;
}
//C is exhausted
while(i<l && j<m){
if(A[i]<=B[j]){
res.push_back(A[i]);
i++;
}
else{
res.push_back(B[j]);
j++;
}
}
//B is exhausted
while(i<l && k<n){
if(A[i]<=C[k]){
res.push_back(A[i]);
i++;
}
else{
res.push_back(C[k]);
k++;
}
}
//A is exhausted
while(k<n && j<m){
if(C[k]<=B[j]){
res.push_back(C[k]);
k++;
}
else{
res.push_back(B[j]);
j++;
}
}
//A is not exhausted
while(i<l){
res.push_back(A[i]);
i++;
}
//B is not exhausted
while(j<m){
res.push_back(B[j]);
j++;
}
//C is not exhausted
while(k<n){
res.push_back(C[k]);
k++;
}
return res;
}