You are on page 1of 5

// Binary search

using namespace std;


void binarySearch(int array[], int lowerbound, int upperbound, int
key)
{
int position;
int comparisonCount = 1; //count the number of
comparisons (optional)

// To start, find the subscript of the middle position.


position = ( lowerbound + upperbound) / 2;

while((array[position] != key) && (lowerbound <= upperbound))


{
comparisonCount++;
if (array[position] > key) // If the
number is > key, ..
{
// decrease position by one.
upperbound = position - 1;
}
else
{
// Else, increase position by one.
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound)
{
cout<< "KEY FOUND !!!!! The number was found in array
subscript "<< position<<endl<<endl;
cout<< "The binary search found the number after " <<
comparisonCount
<< " comparisons.\n";
// printing the number of comparisons is optional
}
else
cout<< "KEY NOT FOUND IN LIST\n "
<<comparisonCount << " comparisons.";
return; // you may also consider returning the subscript
}
int main()
{ void binarySearch(int array[], int lowerbound, int upperbound, int
key);
int s_array[]={12,34,56,78,90,98,102};
int key,lbound, ubound;
cout << "\n Enter lowerbound, upperbound:";
cin >> lbound>>ubound;
cout <<"\n enter key for search:";
cin >> key;
binarySearch(s_array,lbound,ubound,key);
return(0);

You might also like