#include <iostream>
using namespace std;
int MyBinSearch(int a[],int num,int data){
int low,high,mid;
low=0;
high=num-1;
while(low<=high){
mid=(low+high)/2;
if(data>a[mid])
low=mid+1;
else if(data<a[mid])
high=mid-1;
else
return mid;
}
return 0;
}
int BinSearch(int a[],int num,int data){
int low=1,high=num,mid;
while(low<=high){
mid=(low+high)/2;
if(data>a[mid])
low=mid+1;
else if(data<a[mid])
high=mid-1;
else
return mid;
}
return 0;
}
int BinSearchReCursion(int a[],int low,int high,int data){
int mid;
if(low>high)
return 0;
else
{
mid = (low + high)/2;
if(data<a[mid])
return BinSearchReCursion(a,low,mid-1,data);
else if(data>a[mid])
return BinSearchReCursion(a,mid+1,high,data);
else
return mid;
}
}
int main(){
int a[]={1,2,3,4,5};
int pos;
pos=BinSearch(a,5,3);
cout<<pos<<endl;
cout<<"----------------------------------万恶的分割线-------------------------------"<<endl;
pos=MyBinSearch(a,5,3);
cout<<pos<<endl;;
cout<<"----------------------------------万恶的分割线-------------------------------"<<endl;
pos=BinSearchReCursion(a,0,4,3);
cout<<pos;
}
非递归算法很简单,就是个取模操作符/,然后地位上界和下界,
对于递归算法,要找到递归边界,找到在何处自己调用自己,写顺手了,就来了!!