Implementation of halved search swustoj

The implementation of halved search
 1000(ms)
 10000(kb)
 2334 / 9041
Write a program to implement the halved search algorithm.

enter

The first row is the length n of the lookup table
The second row is the data element in the lookup table;
The third line is the key of the data element to look for.

output

If the search is successful, it will return the bit sequence, if it is unsuccessful, it will return -1. The second line is the number of comparisons.

sample input

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

Sample output

-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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324817436&siteId=291194637