C++ Union of Two Arrays














































C++ Union of Two Arrays



Union of two arrays can be defined as the common and distinct elements in between the two arrays.
Give two sorted arrays of size x and y respectively, then find their union.

There are 2 methods to solve this:

1.Generic method: Merge the arrays in such a manner by comparing the values at index in both the arrays while iterating accordingly. Also, care has to be taken for not copying a value again so the previous element should also be compared.

2. Advanced(STL) method: Use set for taking both the arrays in as the data type then copy the data in vector. The set concept allows to get distinct values by itself.

1.Generic method(without STL):

#include <iostream>
using namespace std; 
int* findUnion(int ar1[],int ar2[],int x,int y,int p[]) 
int i=0,j=0,k=0;
int temp[x+y];
while(i<x && j<y){ 
if(ar1[i]<ar2[j]){ 
temp[k]=ar1[i];
++k;++i;}
else if(ar2[j]<ar1[i]){
temp[k]=ar2[j];
++j;++k;}
else
temp[k]=ar2[j]; 
++i;++j;} 
while(i<x){
temp[k]=ar1[i];
++i;++k;}
while(j<y){
temp[k]=ar2[j]; 
++k;++j;}
p=temp;
return p;
void main() 
      //taking input of size and data from user
int x,y;
cin>>x>>y;
int ar1[x],ar2[y],temp[x+y]; 
for(int i=0;i<x;++i)
cin>>ar1[i];
for(int i=0;i<y;++i)
cin>>ar2[i];
      //call by reference
int *res=findUnion(ar1,ar2,x,y,temp),j=0;
cout<<"The union formed by generic method is::"<<endl; 
while(j<(x+y)){
      cout<<*(res+j)<<endl; //pointer points to beginning of array and by iteration we can access memory locations thus getting desired result.
      ++j;}
}

2.Advanced method:


#include <bits/stdc++.h>

using namespace std;

vector<int> findUnion(int arr1[], int arr2[], int n, int m)
{
    set<int>s;
    s.insert(arr1,arr1+n);
    s.insert(arr2,arr2+m);

    vector<int>v;
    for(auto &x:s)// auto is a type of register allowing data type independency
    v.push_back(x);

return v;
} 

int main() {
    int N, M;
    cin >>N >> M;
    int arr1[N];
    int arr2[M];
    for(int i = 0;i<N;i++){
        cin >> arr1[i];
    }
    
    for(int i = 0;i<M;i++){
        cin >> arr2[i];
    }
    
    vector<int> ans = findUnion(arr1,arr2, N, M);
    for(int i: ans)cout<<i<<' ';
    cout << endl;
return 0;

Output::




Comments