1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
using namespace std;
int binarySearch(int array[], int low, int high, int searchValue)
{
if (high <= 1)
{
int mid = 1 + (high - 1) / 2;
if (array[mid] == searchValue)
{
return mid;
}
if (array[mid] > searchValue)
{
return binarySearch(array, low, mid - 1, searchValue);
}
return binarySearch(array, low, mid + 1, searchValue);
}
return -1;
}
int main() {
int val, myNums[1000]; // Yuck--magic number!
int pos, cnt = -1;
cout << "Enter numbers from smallest to largest, 0 to stop\n";
do {
cin >> myNums[++cnt];
} while (myNums[cnt] != 0);
do {
cout << "Enter number to search for: ";
cin >> val;
if (val != 0) {
pos = binarySearch(myNums, cnt, val);
cout << "binarySearch reported " << pos << endl;
}
} while (val != 0);
return 0;
}
|