找回密码
 中文实名注册
搜索
查看: 262|回复: 0

二分查找

[复制链接]

731

主题

577

回帖

2万

积分

管理员

积分
24978
发表于 2025-8-20 13:42:08 | 显示全部楼层 |阅读模式
5
2 5 6 9 10
4
9 6 4 10

[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
const int N = 1e4 + 9;
int a[N], n, m;
int binary_search(int x) {
    int l = 0, r = n - 1;
    while (l <= r) {
        int mid = (l + r) >> 1;
        if (a[mid] < x) {
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }
    return a[l] == x ? l : -1;
}

int main() {
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    cin >> m;
    while (m--) {
        int x;
        cin >> x;
        cout << binary_search(x) << endl;
    }
    return 0;
}


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

快速回复 返回顶部 返回列表