c++简单程序
#include <iostream> using namespace std;
const int size = 10;
void search(const int a[],int first,int last,int key,bool& found,int& laction);
int main()
{
int n;
int a[size];
int first;
int last;
int laction;
bool found;
int key;
for(n=0;n<size;n++)
{
a[n]=n+1;
cout<<a[n]<<" ";
}
cout<<endl;
last=size-1;
cin>>key;
search(a,0,last,key,found,laction);
if(found)
cout<<key<<"laction is :"<<laction<<endl;
else
cout<<key<<"is not laction"<<endl;
return 0;
}
void search(const int a[],int first,int last,int key,bool& found,int& laction)
{
int mid;
if(first > last)
found = false;
else
{
mid=(first + last)/2;
if(key = a[mid])
{
found=true;
laction=mid;
}
else if (key > a[mid])
search(a,mid+1,last,key,found,laction);
else if(key < a[mid])
search(a,first,mid-1,key,found,laction);
}
}
这个是递归的二分法,我的输出总是4,求解决。。。