views:

140

answers:

3

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

thanks.

+4  A: 

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.

Reed Copsey
+1 for the caveat, pointing out that this is a quadratic complexity algorithm and ill-suited for large datasets.
thanks I just added flag and after the loop if else statmentsand done :)thanks
ermac2014
+2  A: 

Assuming both arrays are sorted, you can step them though them like this:

// int array1[FIRSTSIZE];
// int array2[SECONDSIZE];
for(int i=0, j=0; i < FIRSTSIZE && j < SECONDSIZE; ){
    if(array1[i] == array2[j]){
        cout << "DUPLICATE AT POSITION " << i << "," << j << endl;
        i++;
        j++;
    }
    else if(array1[i] < array2[j]){
        i++;
    }
    else{
        j++;
    }
}

This should have linear complexity, but it only works if they're sorted.

Brendan Long
+2  A: 

The solution for sorted arrays has already been posted. If the arrays are not sorted, you can build a set (e.g. std::set or a hash set) out of each and see if the sets are disjoint. You probably have to store value–index pairs in the sets to find out which index was duplicate (and overload the comparison operators appropriately). This might give O(n log n) complexity.

Philipp
I like this answer. I should note: hash sets are implemented in TR1. std::tr1::unordered_set, and boost::unordered_set. TR1 is implemented in both GCC and Visual Studio, so std::tr1::unordered_set ought to be "standard enough". Assuming everything works out with the unordered_set, you should be able to do this in O(n).
Dragontamer5788