c++ 二分查找

        二分查找(Binary Search)是一种在有序数组或列表中查找特定元素的搜索算法。该算法比较要搜索的值和数组的中间元素。如果要搜索的值小于中间元素,则在数组的左半部分继续搜索;如果要搜索的值大于中间元素,则在数组的右半部分继续搜索。通过不断缩小搜索范围,最终可以在O(log n)的时间复杂度内找到目标元素,是一种高效的搜索算法。

C++中实现二分查找的示例代码:

#include <iostream>
#include <vector>

int binarySearch(std::vector<int>& arr, int target) {
    int left = 0;
    int right = arr.size() - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1; // Target not found
}

int main() {
    std::vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15};
    int target = 7;

    int result = binarySearch(arr, target);

    if (result != -1) {
        std::cout << "Target found at index: " << result << std::endl;
    } else {
        std::cout << "Target not found" << std::endl;
    }

    return 0;
}


这段代码演示了一个简单的二分查找函数,用于在一个有序整数数组中查找特定的目标值。

示例二 查找字符串:

        二分查找通常是用于在有序数组中查找数值类型的数据,而不是用于在字符串数组中查找字符串。但是,如果你需要在有序的字符串数组中查找特定的字符串,你可以自定义比较函数来进行二分查找。以下是一个示例代码:

#include <iostream>
#include <vector>
#include <string>

int binarySearchString(std::vector<std::string>& arr, const std::string& target) {
    int left = 0;
    int right = arr.size() - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        int cmp = target.compare(arr[mid]);

        if (cmp == 0) {
            return mid;
        } else if (cmp < 0) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }

    return -1; // Target not found
}

int main() {
    std::vector<std::string> arr = {"apple", "banana", "cherry", "orange", "strawberry"};
    std::string target = "cherry";

    int result = binarySearchString(arr, target);

    if (result != -1) {
        std::cout << "Target found at index: " << result << std::endl;
    } else {
        std::cout << "Target not found" << std::endl;
    }

    return 0;
}


这段代码演示了一个简单的二分查找函数,用于在一个有序的字符串数组中查找特定的目标字符串。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值