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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
using namespace std;
int binarySearch(int[], int, int);
int main()
{
const int SIZE = 34;
int array[SIZE] = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45,
48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90,
93, 96, 99 };
int number, results;
bool valid = false;
cout << "Enter a number between 0 and 99: ";
cin >> number;
results = binarySearch(array, SIZE, number);
if (results == -1)
{
cout << "Enter a number between 0 and 99: ";
cin >> number;
}
else
{
cout << "right " << results;
}
system("pause");
return 0;
}
int binarySearch(int list[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (list[middle] == value)
{
found = true;
position = middle;
}
else if (list[middle] > value)
{
last = middle - 1;
}
else
{
first = middle + 1;
}
}
return position;
}
|