题解 | #查找# 王道机试指南 查找 !二分查找前要排序!
查找
https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN=101;
int str[MAXN];
bool ISinarray(int n,int x)//判断x是否在长度为n的数组中,如果在没返回true。不在,false
{
int mid,low,high;
low=0;//从0开始
high=n-1;
while(low<=high)//循环边界点
{
mid=(high+low)/2;
if(str[mid]==x )
{
return true;
//break;
}
else if(str[mid]<x)
{
low=mid+1;
}
else
high=mid-1;
}
return false;
}
int main()
{
int mx,i;
int m,n;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
scanf("%d",&str[i]);
//排序
sort(str,str+n);
cin>>m;
while(m--)
{
cin>>mx;
if(ISinarray(n,mx))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
return 0;
}
一定要注意 在二分查找之前,一定要先对数组排序,否则输出结果不对