CCBet
CCBet

Reputation: 426

Am I using the boolean operator wrong?

I'm trying to look in a array to see if a precise element (x) is found in it. For this I'm saying at the beginning of the problem that contor=0 (boolean parameter), meaning that there is no x in the array, but if while the for loop is runing and x is found in the array, i said that contor=1 ... and at the end i did the test if(contor) else and it's not working in the case when x is not found in the array. It's just not showing anything. I don't get it ...I'm a beginner. Thank you!

  #include<iostream>

  using namespace std;

  void main()

  {int x, st, dr, m,n,i,contor=0;       //dr = right, st = left, m=middle;
   int v[100];

   cout << "How many elements will the array have?";
   cin >> n;
   cout << endl;

   for (i = 0; i < n;i++)
      {cout << "Insert a element in the array:";
       cin >> v[i];
      }

   cout << "Which is the number you are looking for?";
   cin >> x;

   st = 0;
   dr = n - 1;

   for (i = st; i <= dr;)

      {m = (st + dr) / 2;

      if (v[m] == x)
         { contor = 1;
            break;
         }
      else if (v[m] > x)
          dr = m - 1;
      else st = m + 1;
      }

   if (contor)
       cout << "The element you are looking for is in the array.";
   else
       cout << "The element you are looking for is NOT in the array.";

   cin.get();
   cin.get();
   }

Upvotes: 1

Views: 131

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76988

You are trying to do a binary search, but you do it inside an infinite cycle. If the element is found, you break from the cycle, but if it is not found, your cycle continues endlessly. Also, you try to do a binary search in an array which is not guaranteed to be ordered. Assuming that the array is ordered, which means that:

i <= j <=> v[i] <= v[j]

this is what could work:

do {
    m = (st + dr) / 2;
    if (v[m] == x) {
        contor = 1;
        break;
    } else if (v[m] > x) {
        dr = (st + m - 1) / 2;
    } else {
        st = (m + dr + 1) / 2;
    }
} while (st < dr);

Upvotes: 3

Related Questions