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
|
#include <iostream>
#include <string>
using namespace std;
template<typename T>
T binarySearch( const T list[], T key, int arraySize)
{
int low = 0;
int high = arraySize - 1;
while (high >= low)
{
int mid = (low + high) / 2;
if (key < list[mid])
high = mid -1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -1;
}
int main()
{
int list1[] = {1,8, 15, 25, 33, 100, 200};
cout << "The location of the number you are searching for is " << binarySearch( list1, 15, 7) +1 << " on the list." << endl;
double list2[] = {.125, 1.5, 9.8, 25.68, 98.44};
cout << "The location of the number you are searching for is " << binarySearch( list2, 98.44, 5) +1 << " on the list." << endl;
char list3[] = {'A', 'B', 'D', 'H', 'L', 'M', 'R', 'S', 'T'};
cout << "The location of the letter you are searching for is " << binarySearch( list3, 'M', 9) +1 << " on the list." << endl;
string list4[] = {"So", "Im", "getting", "hungry"};
cout << "The location of the word you are searching for is " << binarySearch( list4, "hungry", 4) +1 << " on the list." << endl;
return 0;
}
|