user3869196
user3869196

Reputation: 32

Checking duplicated numbers in Array

The function should check if there is any duplicated number but it's not working somehow.

anyone knows why?

#include <iostream>

using namespace std;


int main()
{
   int const size = 10;
   int arry[size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};

   int i = 0;
   int k = 1;

   for (i = 0; i < size; i++)
   {
       for (k = 1; k < size; k++)
       {
           if (arry[i] == arry[k])
           {
               cout << arry[i] << " " << arry[k] << endl;
               cout << "duplicate" << endl;
               return 0;
           }
       }
   }
   cout << "no duplicate" << endl;
   return 0;
}

Upvotes: 0

Views: 75

Answers (3)

Jarod42
Jarod42

Reputation: 217293

A more efficient approach should be to sort the array first:

std::vector<int> a = {4, 3, 2, 1, 2, 5, 6};

std::sort(std::begin(a), std::end(a));
for (std::size_t i = 1; i < a.size(); ++i) {
    if (a[i - 1] == a[i]) {
        std::cout << a[i] << " " << a[i] << std::endl;
        std::cout << "duplicate" << std::endl;
        return 0;
    }
}
return 0;

Upvotes: 0

EboMike
EboMike

Reputation: 77752

You're checking every combination twice - for example, you're comparing element 2 with element 5, and then 5 with 2. Aside from the fact that you're also checking an element with itself (which is what timrau's answer is guarding against), you're doing the same work twice.

So try

for (i = 0; i < size; i++)
{
     for (k = i + 1; k < size; k++)

instead.

Your approach still doesn't scale very well, it's essentially O(n^2). It would be faster to sort your array and then look for duplicate neighbors.

Upvotes: 0

timrau
timrau

Reputation: 23058

You should skip when i == k.

for (i = 0; i < size; i++)
{
   for (k = i+1; k < size; k++) // <-- either change HERE
   {
       if (i != k && arry[i] == arry[k])
       //  ^^^^^^ or HERE
       {
           cout << arry[i] << " " << arry[k] << endl;
           cout << "duplicate" << endl;
           return 0;
       }
   }
}

Upvotes: 3

Related Questions