forked from Harshita-Kanal/Data-Structures-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionofarray.cpp
More file actions
62 lines (54 loc) · 843 Bytes
/
unionofarray.cpp
File metadata and controls
62 lines (54 loc) · 843 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
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
//cpp program for union of two array
#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<<"Enter elements of first array in ascending order:\n";
for(i=0;i<n;++i){
cin>>a1[i];
}
cout<<"\nEnter size of second array:";
cin>>m;
cout<<"Enter elements of second array in ascending order:\n";
for(i=0;i<m;++i){
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";
for(i=0;i<k;++i){
cout<<u[i]<<" ";
}
return 0;
}