C++ STL中的Binary search(二分查找) - 王陸 - 博客园 (cnblogs.com)
#include <cstdio>
#include <algorithm>
using namespace std;
int a[100]= {4,10,11,30,69,70,96,100};
int binarySearch(int x,int n)
{
int left =0;
int right=n-1;
while(left<=right)
{
int mid =(left+right)/2;
if(x==a[mid])
{
return mid;
}
if(x>a[mid])
{
left=mid+1;
}
else
{
right =mid-1;
}
}
return -1;//未找到x
}
//二分搜索递归实现
int recurisonBinarySearch(int left,int right,int x)
{
if(left>right)
{
return -1;
}
int mid =(left+right)/2;
if(x==a[mid])
{
return mid;
}
if(x>a[mid])
{
return recurisonBinarySearch(mid+1,right,x);
}
else
{
return recurisonBinarySearch(left,mid-1,x);
}
}
int main()
{
int x;
int ans1,ans2;
scanf("%d",&x);
ans1=binarySearch(x,8);
ans2=recurisonBinarySearch(0,7,x);
printf("%d %d\n",ans1,ans2);
return 0;
}