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 63 64 65 66
|
// p. 271-2, Fig. 4.20
// binary search of an array for a search key
#include <iostream>
#include <iomanip>
using namespace std;
// Binary Search function
int binarySearch (const int b[], int searchKey, int low, int high, int size)
{
int middle;
while (low <= high)
{
middle = (low + high) / 2;
if (searchKey == b[middle]) // match
return middle;
else if (searchKey < b[middle])
high = middle - 1; // search low end of array
else
low = middle + 1; // search high end of array
}
return -1; // searchKey not found
}
// Main program
int main()
{
const int arraySize = 10;
int a[arraySize] = {23, 54, 34, 11, 3, 5465, 73, 77, 534, 99};
int key;
int result;
cout << "Enter a number between 0 and 9999: ";
cin >> key;
result = binarySearch(a, key, 0, arraySize - 1, arraySize);
if (result != -1)
{
cout << '\n' << key << " found in array element " << result << endl;
}
else
{
cout << '\n' << key << " not found" << endl;
}
cin.ignore();
cin.get();
return 0;
}
|