#include<iostream>
#include<algorithm>//使用sort排序函数必须包含此文件头
using namespace std;
int main()
{
int n,a;//n:一共多少个数 a:要找的那个数
int str[10000];
cin>>n>>a;//输入值
for(int i=1;i<=n;i++)
cin>>str[i];
sort(str,str+n);//默认从小到大排序函数
int cns=0;//统计程序执行次数
int t=1;//数组头部下标
int w=n;//数组尾部下标
int xb=0;//下标
while(t<=w)
{
cns++;//计数
int zj=0;
zj=(t+w)/2;//头部和尾部中间那个数的下标 #重点
if(a==str[zj]) //与中间那个数对比
{
xb=zj;//成立就标记下标结束循环
break;
}
else if(str[zj]<a) t=zj+1; //说明这个数在后半部分,把头部缩到中间
else w=zj-1;//说明这个数在前半部分,把尾部缩到中间
}
cout<<xb<<endl;//输出下标
cout<<"一共循环了多少次"<<cns<<endl;//输出程序执行的次数
return 0;
}
二分查找(C/C++详细注释)
猜你喜欢
转载自blog.csdn.net/qq_46232829/article/details/107636446
今日推荐
周排行