二分查找算法代码:
#include<iostream>
using namespace std;
//非递归实现
int FindElement(int a[],int first,int end,int target)
{
int mid,value;
int L=first,R=end;
while(L<R)
{
mid=(L+R)/2;
value=a[mid];
if(value==target)
{
return mid;
}
if(target<value)
{
if(R-L==1)
{
return -1;
}
R=mid;
}
else
{
if(a[R]==target)
{
return target;
}
if(R-L==1)
{
return -1;
}
L=mid;
}
}
return -1;
}
//递归实现
int Findelement(int a[],int first,int end,int target)
{
int mid;
int L=first,R=end;
mid=(L+R)/2;
if(a[mid]==target)
{
return mid;
}
if(mid==end||mid==0)
{
return -1;
}
if(a[mid]>target)
{
if(a[R]==target)
{
return target;
}
R=mid;
return Findelement(a,L,R,target);
}
else
{ if(R-L==1)
{
return -1;
}
L=mid;
return Findelement(a,L,R,target);
}
}
int main()
{
int a[10];
for(int i=0;i<10;i++)
{
a[i]=i*2;
}
int n=Findelement(a,0,10,7);
if(n>=0&&n<10)
cout<<a[n];
else
cout<<"can't find this element!"<<endl;
cout<<endl;
n=FindElement(a,0,10,7);
if(n>=0&&n<10)
cout<<a[n];
else
cout<<"can't find this element!"<<endl;
return 0;
}