I could get this binary search to work... no matter what number i enter it will say
"not found" even if its in the array; until, i sorted the array before searching. So, when making an array to search, i always have to sort it first?

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
   const int size = 100;
   int iarray[size];
   int search, low, high, current;
   
   for(int i = 0; i < size; i++)
      iarray[i] = rand() % 100 + 1;

   for(int i = 0; i < size; i++)
      cout << iarray[i] << ' ';    

   cout << endl << endl;
   cout << "Enter a number to search: ";
   cin >> search;

   while(search != -1)
   {  
      low = 0;
      high = size - 1;
	  while(low <= high)
      {
         current = (low + high) / 2;
         if(search > iarray[current])
             low = current + 1;
         else if(search < iarray[current])
             high = current - 1;
         else
             break;
      }

      if(iarray[current] == search)
          cout << "Found!" << endl;
      else
          cout << "Not found!" << endl;

       cout << "Enter a number to search: ";
       cin >> search;
   }
	
	cin.ignore(1);
	return 0;
}

Recommended Answers

So, when making an array to search, i always have to sort it first?

Yes. It's impossible to do a binary search on an unsorted list.

I could get this binary search to work... no matter what number i enter it will say
"not found" even if its in the …

Jump to Post

All 2 Replies

So, when making an array to search, i always have to sort it first?

Yes. It's impossible to do a binary search on an unsorted list.

I could get this binary search to work... no matter what number i enter it will say
"not found" even if its in the array; until, i sorted the array before searching.

Now is a good time to add debugging statements to follow what the code is actually doing.
Before and after every important decision, display the variables that are affected and study the values to see which ones are not as expected.

You're going to have to desk check your program using this technique -- one of the most important debug techniques in your programming arsenal.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.