8621 二分查找

**思路:**
1. 读取输入的元素个数 `n`。
2. 读取有序数组 `ST`。
3. 读取要查找的关键字 `key`。
4. 使用折半查找法(即二分查找)在数组 `ST` 中查找 `key` 的位置。
5. 如果找到 `key`,输出其位置;如果未找到,输出 "The element is not exist."。

**伪代码:**
1. 读取 `n`。
2. 读取数组 `ST`。
3. 读取 `key`。
4. 初始化 `left` 为 0,`right` 为 `n-1`。
5. 当 `left` 小于等于 `right` 时:
   - 计算 `mid` 为 `(left + right) / 2`。
   - 如果 `ST[mid]` 等于 `key`,输出 `mid` 并返回。
   - 如果 `ST[mid]` 小于 `key`,将 `left` 设为 `mid + 1`。
   - 否则,将 `right` 设为 `mid - 1`。
6. 如果未找到 `key`,输出 "The element is not exist."。

**C++代码:**
 

#include <iostream>
#include <vector>

int Search_Bin(const std::vector<int>& ST, int key) {
    int left = 0;
    int right = ST.size() - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        
        if (ST[mid] == key) {
            return mid;
        } else if (ST[mid] < key) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1; // key not found
}

int main() {
    int n;
    std::cin >> n;
    
    std::vector<int> ST(n);
    for (int i = 0; i < n; ++i) {
        std::cin >> ST[i];
    }
    
    int key;
    std::cin >> key;
    
    int result = Search_Bin(ST, key);
    if (result != -1) {
        std::cout << "The element position is " << result << "." << std::endl;
    } else {
        std::cout << "The element is not exist." << std::endl;
    }
    
    return 0;
}

**总结:**
- 使用二分查找法可以在有序数组中高效地查找元素的位置。
- 通过计算中间位置 `mid` 并调整查找范围,可以在对数时间复杂度内完成查找。
- 如果找到元素,返回其位置;如果未找到,返回 -1 并输出相应信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值