Find Union of Two Arrays in C++
In this tutorial, we will learn how to find the union of two unsorted arrays in C++. Before that let’s first understand what is array.
Array: is a derived data type that contains the same type of data. Like integer array stores values of only integer type, float array stores values of only float type.
Derived data type: is a data type that is defined by the user itself. Other derived data types are Structure, Class, Union, Enumeration, and Pointers.
The union of two arrays: is the set of all elements that are either in A or in B.
Example:
Array1: { 1, 2, 3, 4, 5 }
Array2: { 4, 5, 6, 7, 8, 9, 10 }
The union of given two arrays: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }. Because all these elements are present either in Array1 or in Array2.
(*Note: Array should not contain 1 element twice.)
Program to Find Union of Two Unsorted Arrays in C++
#include<iostream> using namespace std; int main() { int n1,n2,i,j,flag; cout<<"Enter the no. of elements of the 1st array: "; cin>>n1; /* declaring arr1 of size n1 */ int arr1[n1]; cout<<"\nEnter the elements of the 1st array: "; for(i=0;i<n1;i++) { cin>>arr1[i]; } cout<<"\nEnter the no. of elements of the 2nd array: "; cin>>n2; /* declaring arr2 of size n2 */ int arr2[n2]; cout<<"\nEnter the elements of the 2nd array: "; for(i=0;i<n2;i++) { cin>>arr2[i]; } /* printing elements that are either in array1 or in array2 */ cout<<"\nUnion of the two arrays: "; /* First print all the elements of array1 */ for(i=0;i<n1;i++) { cout<<arr1[i]<<" "; } /* Then print all the elements that are in array2 but not in array1 */ for(j=0;j<n2;j++) { flag=0; for(i=0;i<n1;i++) { if(arr1[i]==arr2[j]) { flag=1; break; } } /* flag!=1 means element of array2 is not present in array1 */ if(flag!=1) { cout<<arr2[j]<<" "; } } return 0; }
Input/Output:
Enter the no. of elements of the 1st array: 4 Enter the elements of the 1st array: -3 0 4 7 Enter the no. of elements of the 2nd array: 6 Enter the elements of the 2nd array: 4 1 9 7 2 8 Union of the two arrays: -3 0 4 7 1 9 2 8
Time Complexity
O(n1*n2), where n1 is the no. of elements of the first array and n2 is no. of elements of the second array.
You may also read:
This program will be false for some cases.
One of them is mentioned below :-
Enter the no. of elements of the 1st array: 4
Enter the elements of the 1st array:
1
2
3
1
Enter the no. of elements of the 2nd array: 4
Enter the elements of the 2nd array:
3
4
5
2
Union of the two arrays: 1 2 3 1 4 5