谁帮写几行简单的二分搜索法的程序

来源:百度知道 编辑:UC知道 时间:2024/05/07 08:26:18
按照从小到大的顺序从键盘输入输入一组整数,以二分搜索算法找出50在这组整数中的位置,
例如:若输入1,4,33,50,66,90,输出结果应为4。
若输入整数中不存在50,应输出-1。
用C++

template<class Type>
int BinarySearch(Type a[],const Type&x,int n)
{
int left=0;
int right=n-1;
while (left<=right)
{int middle=(left+right)/2;
if(x==a[middle]) return middle;
if(x>a[middle]) left=middle+1;
else right=middle-1;
}
return -1;

}

void main()
{ int b[]={1,2,3,5,6,8,9}

cout>>"请输入要找的数:">>endl;
cout>>template<class Type>>>endl;

www.vckbase.com去下啊。

你给的分太少了