#include<iostream>
using namespace std;
int BinSearch(int a[],int low, int high, int key)
{
if (low<=high)
{
int mid = (low+high)/2;//一分为二
if(key==a[mid])
return mid;//找到key,返回所在位置(递归结束)
else if(key<a[mid])
return BinSearch(a,low,mid,key);//递归求解
else if(key>a[mid])
return BinSearch(a,mid+1,high,key);//递归求解
}
else
return-1;//未找到返回-1
}
int main() {
int n=0,m,k;
cout<<"输入数组a长度m:";
cin>>m;
int a[m]={12,34,56,78,89,54,23};
cout<<"输入关键字:" ;
cin>>k;
cout<<BinSearch(a,n,m,k);
}
有序序列的二分搜索(递归)算法的设计与实现
最新推荐文章于 2024-09-03 18:29:17 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)