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

   2024-10-13 5960
核心提示:下面是一个示例代码实现C++中的二分查找算法:#include vector#include iostreamint binarySearch(std::vectorint arr, int targ

下面是一个示例代码实现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。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号