-
Notifications
You must be signed in to change notification settings - Fork 22
/
Find Union of two sorted arrays
73 lines (60 loc) · 1.19 KB
/
Find Union of two sorted arrays
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
73
/* C++ Program to find Union of Two Sorted Arrays */
#include<iostream>
using namespace std;
int main()
{
int a1[20],a2[20],u[40],i,j,k,n,m;
cout<<"Enter size of first array: ";
cin>>n;
cout<<"\nEnter elements to the array :: \n";
for(i=0;i<n;++i)
{
cout<<"\nEnter "<<i+1<<" element :: ";
cin>>a1[i];
}
cout<<"\nEnter size of second array: ";
cin>>m;
cout<<"\nEnter elements to the array :: \n";
for(i=0;i<m;++i)
{
cout<<"\nEnter "<<i+1<<" element :: ";
cin>>a2[i];
}
for(i=0,j=0,k=0;i<n&&j<m;){
if(a1[i]<a2[j]){
u[k]=a1[i];
i++;
k++;
}
else if(a1[i]>a2[j]){
u[k]=a2[j];
j++;
k++;
}
else{
u[k]=a1[i];
i++;
j++;
k++;
}
}
if(i<n){
for(;i<n;++i){
u[k]=a1[i];
k++;
}
}
else if(j<m){
for(;j<m;++j){
u[k]=a2[j];
k++;
}
}
cout<<"\nUnion of two arrays is :: \n\n";
for(i=0;i<k;++i)
{
cout<<u[i]<<" ";
}
cout<<"\n";
return 0;
}