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 67 68 69 70 71 72 73 74 75 76 77
|
#include <iostream>
#include <string>
using namespace std;
// template function prototype
template<typename T>
const T *BinarySearch(const T *first, const T *last, T itemToFind)
{
int middle;
bool found = false;
while (first <= last && !found)
{
middle = (first + last) >> 1;
if (itemToFind == first[middle])
return &first[middle];
else
BinarySearch(middle, last, itemToFind);
}
return NULL;
}
/*#include "lab22.C"
template<typename T>
void PrintArray(const T *array, int count)
{
const T *ptr;
const T *const endPtr = array + count;
for (ptr = array; ptr < endPtr; ptr++)
cout << *ptr << " ";
cout << endl;
}
template<typename T>
void PrintAndSearch(const T *array, int n, T itemToFind, string nameOfArray)
{
const T *ptr;
cout << "Array " << nameOfArray << " contains:" << endl;
PrintArray(array, n);
ptr = BinarySearch(array, array + (n - 1), itemToFind);
cout << itemToFind;
if (ptr)
cout << " is in array " << nameOfArray << " and is located at index "
<< ptr - array << endl << endl;
else
cout << " is not in array " << nameOfArray << endl << endl;
}
int main()
{
const int aCount = 5, bCount = 7, cCount = 26, dCount = 10;
int a[aCount] = {5, 15, 25, 35, 45};
double b[bCount] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
char c[cCount] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'};
string d[dCount] = {"Audi", "BMW", "Bentley", "Buick", "Cadillac",
"Chevrolet", "Dodge", "GMC", "Jaguar", "Lexus"};
PrintAndSearch(a, aCount, 25, "a");
PrintAndSearch(a, aCount, 55, "a");
PrintAndSearch(b, bCount, 1.1, "b");
PrintAndSearch(b, bCount, 11.11, "b");
PrintAndSearch(c, cCount, 'z', "c");
PrintAndSearch(c, cCount, 'Z', "c");
PrintAndSearch(d, dCount, static_cast<string>("Cadillac"), "d");
PrintAndSearch(d, dCount, static_cast<string>("Mercedes"), "d");
return 0;
}*/
|