954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Binary sort question

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;
}
fishsticks1907
Newbie Poster
19 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 
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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Thanks for the info!

fishsticks1907
Newbie Poster
19 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You