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;
}