I have two arrays, namely a[] and b[]. I would like to search if any element of a is present in b. Note that I do not want to find all duplicate occurrences, if any one element from a[] exists in b[], I would like to report it and break out without checking the rest of a[] or b[]
I'm a bit confused about how 'break' operates. Can 'break' break out of any kind of loop - for/while, but it breaks out of only the 'innermost loop' around where it's placed in code ?
This is my solution and please suggest if there is a better implementation for this O(n^2) approach
#include <stdio.h>
int main(void)
{
int a[] = {1,2,3,4,5,6};
int b[] = {11,2,3,7,8,9,6,10,11};
int i = 0, j = 0;
int duplicate = 0;
for(i=0;i<sizeof(a)/sizeof(int);i++)
{
for(j=0;j<sizeof(b)/sizeof(int);j++)
{
if(a[i] == b[j])
{
printf("Duplicates found for [%d]\n",a[i]);
duplicate = 1;
break;
}
}
if(duplicate == 1)
{
break;
}
}
return 0;
}
breaks generally break out of the most inner loop in c. You have used it correctly.
if u want to just report a duplicate, then u can put this code into a fuction and whenever a duplicate is found, you just return. The function would look like this:
You cannot use sizeof(a) here becoz its just a pointer to array.Same goes for sizeof(b).
You can make this algorithm more efficient by sorting the arrays using quicksort(that would take O(nlgn)) and then for each element in a do binary search in b.
pseudo code for that is something like this:
So, the whole algorithm works in O(nlgn). While the algorithm you are using can take O(n^2).
Otherwise your code is perfectly fine and the use of break is correct