C program to print union of two arrays
Output:
Enter the size of array A:
5
Enter the elements of array A:
1 2 5 8 9
Enter the size of array B:
5
Enter the elements of array B:
2 4 6 8 10
The union of two arrays is:
1 2 4 5 6 8 9 10
Implementation:
Output:
Enter the size of array A:
5
Enter the elements of array A:
1 2 5 8 9
Enter the size of array B:
5
Enter the elements of array B:
2 4 6 8 10
The union of two arrays is:
1 2 4 5 6 8 9 10
Implementation:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100000
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int main(void) {
int *A,*B,Asize,Bsize;
int i,j,k;
int hash[MAX];
printf("Enter the size of array A:\n");
scanf("%d",&Asize);
A=(int*)malloc(sizeof(int)*Asize);
memset(hash,0,sizeof(hash));
printf("Enter the elements of array A:\n");
for(i=0;i<Asize;i++)
{
scanf("%d",(A+i));
hash[*(A+i)]=1;
}
printf("Enter the size of array B:\n");
scanf("%d",&Bsize);
B=(int*)malloc(sizeof(int)*Bsize);
printf("Enter the elements of array B:\n");
for(i=0;i<Bsize;i++)
{
scanf("%d",(B+i));
}
k=1;
A=realloc(A,(Asize+Bsize));
for(i=0;i<Bsize;i++)
{
if(hash[*(B+i)]==0)
{
A[Asize+k-1]=*(B+i);
k++;
}
}
/* sort the union array */
for(i=0;i<(Asize+k-1)-1;i++)
{
for(j=i+1;j<(Asize+k-1);j++)
{
if(*(A+i)>*(A+j))
{
swap((A+i),(A+j));
}
}
}
printf("The union of two arrays is:\n");
for(i=0;i<(Asize+k-1);i++)
{
printf("%d ",*(A+i));
}
return 0;
}