c++二分查找算法代码怎么写

c++
1116
2024/7/2 9:30:20
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

下面是一个示例代码实现C++中的二分查找算法:

#include <vector>
#include <iostream>

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;
}

int main() {
    std::vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15};
    int target = 9;
    
    int result = binarySearch(arr, target);
    
    if (result != -1) {
        std::cout << "Element found at index: " << result << std::endl;
    } else {
        std::cout << "Element not found in the array" << std::endl;
    }
    
    return 0;
}

在这个示例代码中,binarySearch函数接受一个已排序的整数数组和一个目标值作为参数,然后使用二分查找算法在数组中查找目标值。如果找到目标值,则返回该值在数组中的索引,否则返回-1。在main函数中,我们创建了一个已排序的整数数组并调用binarySearch函数来查找目标值9。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++动态二维数组能否序列化