How to find a union of two arrays in C++

Overview

A union of two sets (A and B) is the set of elements that are in A, in B, or in both A and B.

In C++, Set has a property whereby all the elements it contains are unique.

Example

A = {3,5,7 8,4,9} 
B = {1,2,3,5,9,7,8,6}

AUB = { 3, 5, 7, 8, 4, 9, 1, 2, 6 }

Code

#include <iostream>
using namespace std;
#define sizeOfA 6
#define sizeOfB 8
int findCommonElement(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB)
{
int commonElemnt =0;
for(int i=0; i<sizeOfSetA; i++)
{
for(int j=0; j<sizeOfSetB; j++)
{
if(setA[i]==setB[j])
{
commonElemnt++;
}
}
}
}
int *findUnion(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB, int commonElement)
{
int *unionArray;
// Find the size of the new array
int sizeOfUnionArray= sizeOfSetA + sizeOfSetB - commonElement;
unionArray= new int[sizeOfUnionArray];
int k=0; // Use this iterator to insert elements in the union array
for(int i=0; i<sizeOfSetA; i++)
{
unionArray[k]=setA[i]; // Copy all the element of the array
k++;
}
for(int i=0; i<sizeOfSetB; i++)
{
bool isNotExit= true; // This variable is used to check element is exit or not in unionArray
for(int j=0; j<sizeOfSetA; j++)
{
if (setA[j]==setB[i])// This condition evaluates if element in both arrays is the same or not and change the isNotExit variable accordingly
{
isNotExit= false;
}
}
if(isNotExit)
{
unionArray[k]=setB[i];
k++;
}
}
return unionArray;
}
int main()
{
int * UnionArray;
// Declare two arrays A and B
int A[sizeOfA] = {3,5,7,8,4,9};
int B[sizeOfB] = {1,2,3,5,9,7,8,6};
int commonElement=findCommonElement(A,sizeOfA, B,sizeOfB);// Get the number of the common elements of both arrays
int sizeOfNewArray=sizeOfA+sizeOfB-commonElement;// Calculate the size of the new array
UnionArray=findUnion(A,sizeOfA,B,sizeOfB, commonElement);
//Print the array element
cout<<"{ ";
for(int i= 0; i<=sizeOfNewArray; i++)
{
if(i<sizeOfNewArray)
{
cout<<UnionArray[i]<<", ";
}
else
{
cout<<UnionArray[i]<<" }";
}
}
return 0;
}

Explanation

  • Lines 3 to 4: We define the size of the two arrays, setA and setB.
  • Line 5: We implement the findCommonElement function to find the common element of the two arrays.
  • Line 34 to 37: We already check elment is present in the unionArray or not.
  • Line 19: We implement the findUnion function to find the union of the two arrays.
  • Line 52: We declare the unionArray pointer to allocate memory dynamically, based on the sizeOfUnionArray array.
  • Lines 60 to 71: We print the data of the unionArray.

Free Resources