Skip to content

Commit d2e308b

Browse files
Merge pull request #98 from MonalikaKapoor/Union-of-two-sorted-arrays
Added code to Find Union of two sorted arrays
2 parents eb38541 + b647f3b commit d2e308b

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Find Union of two sorted arrays

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/* C++ Program to find Union of Two Sorted Arrays */
2+
3+
#include<iostream>
4+
5+
using namespace std;
6+
7+
int main()
8+
{
9+
int a1[20],a2[20],u[40],i,j,k,n,m;
10+
11+
cout<<"Enter size of first array: ";
12+
cin>>n;
13+
cout<<"\nEnter elements to the array :: \n";
14+
15+
for(i=0;i<n;++i)
16+
{
17+
cout<<"\nEnter "<<i+1<<" element :: ";
18+
cin>>a1[i];
19+
}
20+
21+
cout<<"\nEnter size of second array: ";
22+
cin>>m;
23+
cout<<"\nEnter elements to the array :: \n";
24+
25+
for(i=0;i<m;++i)
26+
{
27+
cout<<"\nEnter "<<i+1<<" element :: ";
28+
cin>>a2[i];
29+
}
30+
31+
32+
for(i=0,j=0,k=0;i<n&&j<m;){
33+
if(a1[i]<a2[j]){
34+
u[k]=a1[i];
35+
i++;
36+
k++;
37+
}
38+
else if(a1[i]>a2[j]){
39+
u[k]=a2[j];
40+
j++;
41+
k++;
42+
}
43+
else{
44+
u[k]=a1[i];
45+
i++;
46+
j++;
47+
k++;
48+
}
49+
}
50+
51+
if(i<n){
52+
for(;i<n;++i){
53+
u[k]=a1[i];
54+
k++;
55+
}
56+
}
57+
else if(j<m){
58+
for(;j<m;++j){
59+
u[k]=a2[j];
60+
k++;
61+
}
62+
}
63+
64+
cout<<"\nUnion of two arrays is :: \n\n";
65+
for(i=0;i<k;++i)
66+
{
67+
cout<<u[i]<<" ";
68+
}
69+
70+
cout<<"\n";
71+
72+
return 0;
73+
}

0 commit comments

Comments
 (0)