二分搜索(暑假)

题目描述:在有序序列中查找某一元素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 <iostream>
using namespace std;
const int N = 1000000 + 10;
int a[N];
int main()
{
    int n;
    cin >> n;
    for(int i = 0;i < n ;i ++ )cin >> a[i];
    int m;
    cin >> m;
    while(m -- )
    {
        int x;
        cin >> x;
        int l = 0,r = n - 1;
        while(l < r)
        {
            int mid = l + r >> 1;
            if(a[mid] >= x)r = mid;
            else l = mid + 1;
        }
        if(a[l] == x)cout << l << endl;
        else cout << "Not found!" << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值