Examples :
Input:
arr1[ ] = {2, 4, 5, 7, 8}
arr2[ ] = {1, 2, 4, 5, 8}
Output Intersection: 2 4 5 8
Intersection :
#include <bits/stdc++.h>
using namespace std;
void arrayIntersection(int arr1[], int arr2[], int n1, int n2)
{
int i = 0, j = 0;
while (i < n1 && j < n2)
{
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
cout << arr2[j] << " ";
i++;
j++;
}
}
}
// main function
int main()
{
int arr1[100], arr2[100], n1, n2;
cout << "Enter Number of elements for array 1: ";
cin >> n1;
for (int i = 0; i < n1; i++)
{
cin >> arr1[i];
}
cout << "Enter Number of elements for array 2: ";
cin >> n2;
for (int j = 0; j < n2; j++)
{
cin >> arr2[j];
}
arrayIntersection(arr1, arr2, n1, n2);
return 0;
}
Output:
Enter Number of elements for array 1: 5
1 2 3 4 5
Enter Number of elements for array 2: 5
3 4 5 6 7
3 4 5
0 Comments