C Program to Find Common Array Elements Between Two Arrays
Last Updated :
07 Aug, 2022
Here we will build a C Program to Find Common Array Elements between Two Arrays. Given two arrays we have to find common elements in them using the below 2 approaches:
- Using Brute force
- Using Merge Sort and then Traversing
Input:
array1[] = {8, 2, 3, 4, 5, 6, 7, 1}
array2[] = {4, 5, 7, 11, 6, 1}
Output:
Common elements are: 4 5 6 7 1
Approach 1:
This is a brute force approach, simply traverse in the first array, for every element of the first array traverse in the second array to find whether it exists there or not, if true then check it in the result array (to avoid repetition), after that if we found that this element is not present in result array then print it and store it in the result array.
C
#include <stdio.h>
int main()
{
int array1[] = { 8, 2, 3, 4, 5, 6, 7, 1 };
int array2[] = { 4, 5, 7, 11, 6, 1 };
int i, j, flag, x, k = 0;
int result[100];
printf ( "Common elements are: " );
for (i = 0; i < sizeof (array1) / 4; i++) {
for (j = 0; j < sizeof (array2) / 4; j++) {
if (array1[i] == array2[j]) {
flag = 0;
for (x = 0; x < k; x++) {
if (result[x] == array1[i]) {
flag++;
}
}
if (flag == 0) {
result[k] = array1[i];
printf ( "%d " , result[k]);
k++;
}
}
}
}
}
|
Output
Common elements are: 4 5 6 7 1
Time Complexity: O(m*n*k)
Auxiliary Space: O(max(m,n)), as in worst case all the elements could be distinct and common.
Approach 2:
This logic can be applied to the sorted array, if the sorted array is not given then sort it using merge sort as its time complexity is less and then apply this approach.
- Traverse in an array using two variables, i for array1 and j for array2.
- Check if the element of array1 is less than the element of array2 then i++.
- Check if the element of array2 is less than the element of array1 then j++.
- Check if the element of array1 is equal to the element of array2 then check whether it is printed before or not if not then print it and store it in the result array.
C++
#include <stdio.h>
int main()
{
int array1[] = { 1, 2, 2, 3, 5, 6, 7, 8, 18, 29, 37 };
int array2[] = { 2, 2, 4, 5, 7, 9, 10, 18 };
int i = 0, j = 0, flag, x, k = 0;
int result[100];
int array1_size = sizeof (array1) / sizeof (array1[0]);
int array2_size = sizeof (array2) / sizeof (array2[0]);
printf ( "Common elements are: " );
while (i < array1_size && j < array2_size) {
if (array1[i] < array2[j]) {
i++;
}
else if (array1[i] > array2[j]) {
j++;
}
else {
flag = 0;
for (x = 0; x < k; x++) {
if (result[x] == array1[i]) {
flag++;
}
}
if (flag == 0) {
printf ( "%d " , array1[i]);
result[k] = array1[i];
k++;
}
i++;
j++;
}
}
}
|
Output
Common elements are: 2 5 7 18
Time Complexity: O((m+n)*k)
Auxiliary Space: O(max(m,n)), as in worst case all the elements could be distinct and common.
Share your thoughts in the comments
Please Login to comment...