#include<iostream>
using namespace std;
#define MAXSIZE 1000
template<class Type>
//在n个数中使用二分查找
int BinarySearch(Type a[],const Type& x,int n)
{
int left=0;int right=n-1;
while(left<=right)
{
int middle;
middle=(left+right)/2;
if(x==a[middle])
return middle;
if(x>a[middle])
left=middle+1;
else
right=middle-1;
}
return -1;
}
//对自然数的二分查找
int main()
{
int a[MAXSIZE];
int k=0;
int x;
cout<<"请从小到大输入你的查找范围,请务必输入自然数(以-1结束):"<<endl;
int m;
cin>>m;
while(m!=-1)
{
if(m<0)
{
cout<<"Your input is illegal!Please try again:";
}
else
{
a[k]=m;
k++;
}
cin>>m;
}
cout<<"Please input the number you want to search:";
cin>>x;
cout<<"位置是:"<<"a["<<BinarySearch(a,x,k)<<"]"<<endl;
return 0;
}
注意这里的数不能乱输
二分查找
最新推荐文章于 2024-03-28 21:02:15 发布