Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 elements of two arrays in C++

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??

like image 309
Desolator Avatar asked Dec 17 '22 23:12

Desolator


1 Answers

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.

like image 156
Reed Copsey Avatar answered Dec 19 '22 12:12

Reed Copsey