ZZULIOJ 1152: 二分搜索

题目描述在有序序列中查找某一元素x。
输入首先输入一个正整数n(n<=100000),表示该序列有n个整数,然后按从小到大的顺序输入n个整数;
接着是一个正整数m,表示有m次查找;
最后是m个整数,表示m个要查找的整数x。
输出对于每一次查找,有一行输出。若序列中存在要查找的元素x,则输出元素x在序列中的序号(序号从0开始);若序列中不存在要查找的元素x,则输出"Not found!"。
样例输入5
1 3 5 7 9
11
-1
1
2
3
4
5
6
7
8
9
10

样例输出Not found!
0
Not found!
1
Not found!
2
Not found!
3
Not found!
4
Not found!

#include<bits/stdc++.h>
using namespace std;
void cz(int a[],int t,int n);
int main(){
     int m,t,j,i,n;
     cin>>t;
      int a[100010];
     for(i=0;i<t;i++)
       cin>>a[i];
       cin>>m;
        while(m--){
       cin>>n;
       cz(a,t,n);
    }
   return 0;
}
void cz(int a[],int t,int n){
 int i,j,k,p=0;
 i=0,j=t-1;
 while(i<=j){
  k=(i+j)/2;
  if(a[k]==n){ 
  p=k;
  break;
  }
  else if(a[k]>n)j=k-1;
  else i=k+1;
 }
 if(i<=j) cout<<p<<endl;
 else cout<<"Not found!"<<endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_43731933/article/details/84640031