首页 > 代码库 > 二分查找

二分查找

#include <iostream>
using namespace std;
int bs(int a[] ,int n,int hight,int low ,int mid)
{
while (hight>=low)
{
mid=(hight+low)/2;
if(a[mid]==n)
{
return mid;
}
else if (a[mid]<n)
{
low=mid+1;
}
else
{
hight =mid-1;
}
}
return -1;
}
int main()
{
int n,k,a[10]={0,1,2,3,4,5,6,7,8,9};
while (cin >> n)
{
k=bs(a,n,10,0,5);
if (k!=-1)
{
cout << "找到第" << k << "个数是n的值" << endl;
}
else
{
cout << "找不到所要的数" << endl;
}
}
return 0;
}

二分查找