Find Union and Intersection of two unsorted arrays in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to write a program for union and intersection of two unsorted arrays. Let's see an example.

Input 

arr_one = [1, 2, 3, 4, 5]
arr_two = [3, 4, 5, 6, 7]

Output 

union: 1 2 3 4 5 6 7
intersection: 3 4 5

Let's see the steps to solve the problem.

Union

  • Initialize the two arrays with random values.

  • Create an empty array called union_result.

  • Iterate over the first array and add every element to it.

  • Iterate over the section array and add element if it is not present in union_result array.

  • Print the union_result array.

Intersection

  • Initialize the two arrays with random values.

  • Create an empty array called intersection_result.

  • Iterate over the first array and add element if it is present in second array.

  • Print the intersection_result array.

Example

See the code below

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int isElementPresentInArray(int arr[], int arr_length, int element) {
   for (int i = 0; i < arr_length; ++i) {
      if (arr[i] == element) {
         return true;
      }
   }
   return false;
}
void findUnionAndIntersection(int arr_one[], int arr_one_length, int arr_two[], int arr_two_length) {
   // union
   int union_result[arr_one_length + arr_two_length] = {};
   for (int i = 0; i < arr_one_length; ++i) {
      union_result[i] = arr_one[i];
   }
   int union_index = arr_one_length;
   for (int i = 0; i < arr_two_length; ++i) {
      if (!isElementPresentInArray(arr_one, arr_one_length, arr_two[i])) {
         union_result[union_index++] = arr_two[i];
      }
   }
   cout << "Union: ";
   for (int i = 0; i < union_index; ++i) {
      cout << union_result[i] << " ";
   }
   cout << endl;
   // intersection
   int intersection_result[arr_one_length + arr_two_length] = {};
   int intersection_index = 0;
   for (int i = 0; i < arr_one_length; ++i) {
      if (isElementPresentInArray(arr_two, arr_two_length, arr_two[i])) {
         intersection_result[intersection_index++] = arr_one[i];
      }
   }
   cout << "Intersection: ";
   for (int i = 0; i < intersection_index; ++i) {
      cout << intersection_result[i] << " ";
   }
   cout << endl;
}
int main() {
   int arr_one[] = {1, 2, 3, 4, 5};
   int arr_two[] = {3, 4, 5, 6, 7};
   findUnionAndIntersection(arr_one, 5, arr_two, 5);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

Union: 1 2 3 4 5 6 7
Intersection: 1 2 3 4 5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 10:41:30
Advertisements