今天学完二分,来讲一讲 二分查找就是从数中折半寻找 如: 100 - 50,大了- 25,小了- 75 是一种快速查数的方式
假设让机器在数组中找出值x的位置
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}输入数组个数和数组
int x;
cin>>x;输入x 重点:
a[0]=-1e9;
a[n+1]=1e9;把数组边界上放两个“哨兵” 每次查l+r/2(l代表左边端点,r代表右边端点)(中间),查不到边缘上的数,所以放上两个哨兵。
int l=1-1,r=n+1;放了哨兵👆,所以端点从0(1-1)和n+1开始。
while(l+1<r)//直到两个端点快碰上时结束
{
int m=(l+r)/2;//中间=l+(r-l)/2=l+r/2-l/2=r/2+l/2=(r+l)/2
if(a[m]>x)//如果a的m号下标大于给的数
{
r=m;//右端点变为中间
}
else if(a[m]<x)//如果a的m号下标小于给的数
{
l=m;//左端点变为中间
}
else//如果a的m号下标等于给的数
{
cout<<m;//输出中间
return 0;//结束
}
}如果数大了,右端点变小 如果数小了,左端点变大
cout<<-1;如果端点碰上了还没输出结束,那么输出-1。
如果要求找第一个出现的x
else
{
r=m;
}如果等于,右端点继续变小找第一个出现的。
if(a[r]!=x)
{
cout<<-1<<" ";
}
else
{
cout<<r<<" ";
}如果a的r号下标不等于x,输出-1,否则输出r(第一个出现位置)ps:如果找最后出现把r=m改l=m,a[r]改a[l],r改l。
最后上代码
#include<bits/stdc++.h>
using namespace std;
int a[1000005];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
int x;
cin>>x;
a[0]=-1e9;
a[n+1]=1e9;
int l=1-1,r=n+1;
while(l+1<r)
{
int m=(l+r)/2;
if(a[m]>x)
{
r=m;
}
else if(a[m]<x)
{
l=m;
}
else
{
cout<<m;
return 0;
}
}
cout<<-1;
return 0;
}#include<bits/stdc++.h>
using namespace std;
int a[1000005];
int main()
{
int n,q,x;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cin>>q;
while(q--)
{
cin>>x;
a[0]=-1e9;
a[n+1]=1e9;
int l=1-1,r=n+1;
while(l+1<r)
{
int m=(l+r)/2;
if(a[m]>x)
{
r=m;
}
else if(a[m]<x)
{
l=m;
}
else
{
r=m;
}
}
if(a[r]!=x)
{
cout<<-1<<" ";
}
else
{
cout<<r<<" ";
}
}
return 0;
}第一篇专栏,感谢观看,如有问题欢迎评论 谢谢