天马行空  
I ---- Inject 投入 L ---- Loyal 忠诚 O ---- Observant 用心 V ---- Valiant 勇敢 E ---- Enjoyment 喜悦 Y ---- Yes 愿意 O ---- Obligation 责任

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;
}

posted on 2021-10-25 19:55  浅蓝  阅读(33)  评论(0编辑  收藏  举报