折半查找递归算法跟迭代算法:
#include <iostream>
using namespace std;
int diedai(int *a,const int x,const int n);
int digui(int *a,const int x,const int left,const int right);
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10};
int num=1;
//9为数组的下标
int o=digui(a,num,0,9);
if(o<0)
cout<<"递归:对不起没有找到!"<<endl;
else
cout<<"递归:在a["<<o<<"]中找到"<<num<<endl;
//10为数据的个数
int b=diedai(a,num,10);
if(b<0)
cout<<"迭代:对不起没有找到!"<<endl;
else
cout<<"迭代:在a["<<o<<"]中找到"<<num<<endl;
return 0;
}
int diedai(int *a,const int x,const int n){
int left=0,right=n-1;
while(left<=right){
int mid=(left+right)/2;
if(x<a[mid]) right=mid-1;
else if(x>a[mid]) left=mid+1;
else return mid;
}
return -1;
}
int digui(int *a,const int x,const int left,const int right){
if(left<=right){
int mid=(left+right)/2;
if(x<a[mid]) return digui(a,x,left,mid-1);
else if(x>a[mid]) return digui(a,x,mid+1,right);
else return mid;
}
return -1;
}