-
Notifications
You must be signed in to change notification settings - Fork 0
/
union.cpp
74 lines (70 loc) · 1.6 KB
/
union.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
73
74
//Set operation - Union on Arrays by Vishruth Codes
#include<stdio.h>
void displayed(int a[], int n)
{
for(int i=0;i<n;i++)
{
if(i==n-1)
{
printf("%d.",a[i]);
}
else{
printf("%d, ",a[i]);
}
}
}
int unions(int a[], int n, int b[], int m, int res[])
{
int i=0,k=0,t=0,count=0;
//Copying the elements of first array into the result array.
while(i<n)
{
res[t++]=a[i++];
}
while(i<m+n && k<m)
{
int j=0;
while(j<i+1)
{
if (res[j]==b[k])
{
k++;
//the value of i should be updated only is the adjacent space is occupied.
//Here, adjacent space is not occupied, hence to prevent jump to next space
//we write i--
i--;
break;
}
else if(j==i)
{
res[j]=b[k];
k++;
count++;
break;
}
else{
j++;
}
}
i++;
}
return (n+count);
}
int main()
{
int n,m;
int ar1[]={1,4,9,16,32};
int ar2[]={1,2,3,4,5,6,7,8,9,10};
n=sizeof(ar1)/sizeof(ar1[0]);
printf("\nArray1: ");
displayed(ar1,n);
m=sizeof(ar2)/sizeof(ar2[0]);
printf("\nArray2: ");
displayed(ar2,m);
int un[n+m];
int size=unions(ar1,n,ar2,m,un);
//Here size is the length of union
printf("\nThe union: ");
displayed(un,size);
return 0;
}