Union of 2 arrays Algorithm

The Union of 2 arrays algorithm is a technique that combines the elements of two different arrays into a single array, without any duplicates. This algorithm works by iterating through both input arrays and comparing the elements within them, ensuring that any unique values are added to a new array – the result of the union operation. The fundamental goal is to create a new array which contains all the distinct elements from both input arrays. To implement the Union of 2 arrays algorithm, one typically starts by initializing an empty array, which will be used to store the unique elements from both input arrays. Then, iterate through the first input array, adding its elements to the new array if they are not already present. Next, iterate through the second input array, and similarly, add its elements to the new array if they are not already present. This process may involve checking each element in the new array, comparing it with the current element from the input arrays, and only adding it if a match is not found. Once both input arrays have been iterated through, the new array will contain the union of both arrays, with all unique elements represented exactly once.
#include <iostream>
int main()
{
  int m, n, i = 0, j = 0;
  cout << "Enter size of both arrays:";
  cin >> m >> n;
  int a[m];
  int b[n];
  cout << "Enter elements of array 1:";
  for (i = 0; i < m; i++)
    cin >> a[i];
  cout << "Enter elements of array 2:";
  for (i = 0; i < n; i++)
    cin >> b[i];
  i = 0;
  j = 0;
  while ((i < m) && (j < n))
  {
    if (a[i] < b[j])
      cout << a[i++] << " ";
    else if (a[i] > b[j])
      cout << b[j++] << " ";
    else
    {
      cout << a[i++];
      j++;
    }
  }
  while (i < m)
    cout << a[i++] << " ";
  while (j < n)
    cout << b[j++] << " ";
  return 0;
}

LANGUAGE:

DARK MODE: