Find The Common Elements In Two Arrays In C++
Code snippet for how to Find The Common Elements In Two Arrays In C++ with sample and detail explanation
Finding the common elements in two arrays is a fundamental part of understanding how to manipulate and compare data in C++. This topic is crucial for tasks such as data analysis, where we need to find common data points between two sets or arrays.
Code snippet for Finding the Common Elements in two Arrays
The following is a function in C++ that will help you find common elements in two arrays.
#include<iostream>
#include<algorithm>
void findCommon(int array1[], int array2[], int n, int m) {
std::sort(array1, array1 + n);
std::sort(array2, array2 + m);
int i = 0, j = 0;
while (i < n && j < m) {
if (array1[i] < array2[j])
i++;
else if (array2[j] < array1[i])
j++;
else
{
std::cout << array2[j] << " ";
i++;
j++;
}
}
}
int main() {
int array1[] = {1, 2, 3, 4, 5};
int array2[] = {3, 4, 5, 6, 7};
int n = sizeof(array1) / sizeof(array1[0]);
int m = sizeof(array2) / sizeof(array2[0]);
findCommon(array1, array2, n, m);
return 0;
}
Code Explanation for Finding the Common Elements in two Arrays
In this simple program, we first include the standard I/O and algorithm libraries. Then we define a function called findCommon
. This function takes in two arrays and their size.
We begin by sorting both arrays to assure that when we compare elements, we are comparing them in an orderly manner. We do this by utilizing the std::sort
function from the algorithm library.
The while
loop is where the magic happens. Since the arrays are sorted, identical numbers will be aligned with each other - if they exist. So, if the same numbers exist in the two arrays, they will appear at the same index after sorting.
Inside the loop, we have three conditions: If the element in array1 is smaller, we increment the index of array1. If the element in array2 is smaller, we move to the next element in array2. If both elements are the same, we print the common element and move to the next elements in both arrays.
After defining this function, in the main
function, we create two arrays and calculate their sizes. Then, we call the findCommon
function, passing the two arrays and their sizes as arguments.
When the findCommon
function is called, it prints out common elements between the two arrays. For our specific test case, the output would be “3 4 5”.