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
|
#include <iostream>
using namespace std;
int BinSearch(int sortedArray[], int numElements, int searchKey)
{
int first, last, middle;
first = 0;
last = numElements - 1;
while (first <= last)
{
middle = (first + last) / 2;
if( searchKey > sortedArray[middle])
first = middle + 1;
else if (searchKey < sortedArray[middle])
last = middle - 1;
else //(searchKey == sortedArray[middle])
return middle;
}
return -1;
}
int main()
{
char inputChar = 88;
const int numElements = 23;
int sortedArray[numElements] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int searchKey, location;
cout << " {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95}" << endl;
while(true)
{
cout << "Enter search key (or 'x' to exit): ";
cin >> searchKey;
location = BinSearch(sortedArray, numElements, searchKey);
if (location > -1)
cout << searchKey << " is in position " << location << "." << endl;
else if( searchKey == inputChar )
{
cout << "Exiting..." << endl;
break;
}
else
cout << searchKey << " not found." << endl;
}
}
|