C++ 二分法查找

2025-03-19 05:52:32
推荐回答(3个)
回答1:

#include
using namespace std;
int main()
{
void binarysearch(int[],int);
int a[]={2,3,6,11,20,25,33,36,56,58,59,69,76,86,89,99};
int i;
for(i=0;i<16;i++)
{
cout< }
cout< cout<<"input the no you will search:"< int no;
cin>>no;
cout<<"input the number:"< int b[20];
for(i=0;i cin>>b[i];
cout<<"now implement the search:"< for(i=0;i {
binarysearch(a,b[i]);
}
return 0;
}

void binarysearch(int a[],int key)
{
int low=0,high=15,mid;int found=0;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key) found=1;
else if(a[mid] low=mid+1;
else
high=mid-1;
}
if(found)
cout< else
cout<}

回答2:

if(a[mid]==key) found=1;改为:
if(a[mid]==key) { found=1;break;}

回答3:

#include
using namespace std;
int main()
{
void binarysearch(int[],int);
int a[]={2,3,6,11,20,25,33,36,56,58,59,69,76,86,89,99};
int i;
for(i=0;i<16;i++)
{
cout< }
cout< //cout<<"input the no you will search:"< cout<<"input the number:"< int no;
cin>>no;

int b[20];
for(i=0;i {
cin>>b[i];
}
cout<<"now implement the search:"< for(i=0;i {
binarysearch(a,b[i]);
}
cout< return 0;
}

void binarysearch(int a[],int key)
{
int low=0,high=15,mid;int found=0;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
{
found=1;
break;
}
else if(a[mid] {
low=mid+1;
}
else
{
high=mid-1;
}
}

if(found)
{
cout< }
else
{
cout< }
}
////////////////////调试过完全OK的