初始化int类型数组data1={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20},提示用户输入一个数字,应用折半查找函数模板找出它的位置。
#include
using namespace std;
template
int BinSearch(T list[],int n,T key)
{
int mid,low,high;
T midvalue;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
midvalue=list[mid];
if(key==midvalue)
return mid;
else if(key>midvalue)
low=mid+1;
else
high=mid-1;
}
return -1;
}
int main()
{
int key,mid,n=20;
int data1[]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20};
cout<<"Please input a key:"<
cout<