折半查找的实现 swustoj

折半查找的实现
 1000(ms)
 10000(kb)
 2334 / 9041
编写程序实现折半查找算法。

输入

第一行是查找表的长度n
第二行是查找表中的数据元素 ;
第三行是要查找的数据元素的关键字.

输出

查找成功返回位序,不成功返回-1 ,第二行为比较的次数。

样例输入

11
5 13 19 21 37 56 64 75 80 88 92
100

样例输出

-1
4

#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;
int main()
{
int n;
int flag=1;
int num=0;
cin>>n;
vector<int>a(n);
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int m;
cin>>m;
int first=0,final=n-1;
while(n)
{
int t=(first+final)/2;
if(m==a[t]) 
{
cout<<t<<endl;
flag=0;
break;
}
if(m>a[t]) first=t;
if(m<a[t]) final=t;
num++;
n/=2;
}
if(flag) cout<<"-1"<<endl;
cout<<num;
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40328281/article/details/80074258
今日推荐