I have two arrays each array has some values for instance:
int a[] = {1, 2, 3, 4};
int b[] = {0, 1, 5, 6};
now I need to compare the elements of the array (a) with elements in array (b).. if is there any match the program should return an error or print "error there is a duplicate value" etc.. in the above situation, it should return an error coz a[0] = b[1] because both are have same values.
How can I do this??
If the arrays are this small, I would just do a brute force approach, and loop through both arrays:
for (int i=0;i<4;++i)
{
for (int j=0;j<4;++j)
{
if (a[i] == b[j])
{
// Return an error, or print "error there is a duplicate value" etc
}
}
}
If you're going to be dealing with large arrays, you may want to consider a better algorithm, however, as this is O(n^2).
If, for example, one of your arrays is sorted, you could check for matches much more quickly, especially as the length of the array(s) gets larger. I wouldn't bother with anything more elaborate, though, if your arrays are always going to always be a few elements in length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With