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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
#include <iostream>
using namespace std;
class Age
{
private:
int age;
public:
int operator = (int);
};
int Age::operator=(int num)
{
age = num;
}
// iterative
template <class T>
T bsearch(T a[], int sizee, T x)
{
int low = 0;
int high = sizee -1;
while(low <= high)
{
int mid = (low+high)/2;
if(x < a[mid])
high = mid - 1;
else if(x > a[mid])
low = mid + 1;
else
return a[mid];
}
return -1;
}
void print(int val)
{
if(val == -1)
cout << "not found" << endl;
else
cout << "found" << endl;
}
int main()
{
int a[5] = {3, 7, 9, 16, 23};
char b[5] = {'a', 'b', 'c', 'd', 'e'};
float c[5] = {0.1, 0.2, 0.3, 0.4, 0.5};
Age people = {3,6,8,11,22};
int arraySize = 5;
int result;
float input;
result = bsearch(a, arraySize, 7);
print(result);
result = bsearch(a, arraySize, 16);
print(result);
result = bsearch(a, arraySize, 77);
print(result);
cout << endl << endl;
result = bsearch(b, arraySize, 'a');
print(result);
result = bsearch(b, arraySize, 'z');
print(result);
result = bsearch(b, arraySize, 'e');
print(result);
cout << endl << endl;
input = 0.11;
result = bsearch(c, arraySize, input);
print(result);
input = 0.7;
result = bsearch(c, arraySize, input);
print(result);
input = 0.1;
result = bsearch(c, arraySize, input);
print(result);
cout << endl << endl;
result = bsearch(people, arraySize, 22);
print(result);
return 0;
}
|