以下为二分查找的模板函数:
#include <iostream>
using namespace std;
template <class T1,class T2>
int Binary_find(T1 t[],int nSize ,T2 value)
{
int left = 0;
int right = nSize - 1;
int mid = 0;
bool bFind = false;
while (1 && (right >= left))
{
mid = (left + right ) / 2;
if (t[mid] == value)
{
bFind = true;
break;
}
if (t[mid] < value)
{
left = mid + 1;
}
if (t[mid] > value)
{
right = mid - 1;
}
}
int pos = bFind == true ? mid : -1;
return pos;
}
int main()
{
int a[] = {1,3,5,7,9,11,13,15,17,19};
int pos1 = Binary_find(a,10,13);
int pos2 = Binary_find(a,10,8);
return 0;
}