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
|
#include <iostream>
#include <string>
using namespace std;
template< class T, class compare_less >
int array_binary_search(T a[], int low, int high, T target) {
while (low <= high) {
int middle = low + (high - low)/2;
if (compare_less(target, a[middle]))
high = middle - 1;
else if (compare_less(a[middle], target))
low = middle + 1;
else
return middle;
}
return -1;
}
int main()
{
int A[] = { 1, 2, 3, 3, 3, 5, 8 };
const int N = sizeof(A) / sizeof(int);
for (int i = 1; i <= 10; ++i) {
cout << "Searching for " << i << ": ";
array_binary_search(A, 0, N, A[i]);
return 0;
}
| |