#include<iostream>
#include<string>
using namespace std;
bool BinarySearch(int info[], int, int, int, int& istep);
int main()
{
int istep;
int info[10] = {2, 6, 9, 14, 23, 65, 92, 96, 99, 100};
int fromLocation, toLocation, item;
string cmd;
do{
cout << "Insert item, from location and to location" << endl;
cin >> item;
cin >> fromLocation;
cin >> toLocation;
if(fromLocation < 0 || fromLocation > 9 || toLocation > 9 || toLocation < 0)
continue;
BinarySearch(info, item, fromLocation, toLocation, istep);
cout << "Would you like to exit? type 'exit' to exit or type 'yes' to go again" << endl;
cin >> cmd;
}while(cmd != "exit");
}
bool BinarySearch(int info[], int item, int fromLoc, int toLoc, int &istep) {
istep = 0;
if (fromLoc > toLoc)
return false;
int midValue = (toLoc - fromLoc)/2;
if (item == info[midValue])
{
++istep;
cout << "Yes, value found at step " << istep << endl;
return true;
} else if (item < info[midValue])
{
return BinarySearch(info, item, fromLoc, midValue - 1, ++istep);
} else if(item > info[midValue])
{
return BinarySearch(info, item, midValue + 1, toLoc, ++istep);
}
} |