算法基础 - 二分查找

文章目录

二分查找算法通常应用于已排序的数组。以下是一个C++实现的二分查找算法示例:

cpp 复制代码
#include <iostream>
#include <vector>
 
int binarySearch(const std::vector<int>& nums, int target) 
{
    int left = 0;
    int right = nums.size() - 1;
 
    while (left <= right) 
    {
        int mid = left + (right - left) / 2;
        
        if (nums[mid] == target) 
        {
            return mid; // 目标值在数组中的索引
        } 
        else if (nums[mid] < target) 
        {
            left = mid + 1;
        } 
        else 
        {
            right = mid - 1;
        }
        
    }
 
    return -1; // 未找到目标值
}

 
int main() 
{
    std::vector<int> nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
    int target = 23;
    int index = binarySearch(nums, target);
 
    if (index != -1) 
    {
        std::cout << "Element found at index " << index << std::endl;
    } 
    else 
    {
    
        std::cout << "Element not found" << std::endl;
    }
 
    return 0;
}

这段代码定义了一个binarySearch函数,它接受一个整数向量和一个目标值,返回目标值在数组中的索引,如果不存在则返回-1。在main函数中,我们创建了一个已排序的整数数组和一个要查找的目标值,然后调用binarySearch函数并输出结果。

相关推荐
阿Y加油吧10 分钟前
两道经典 DP 题:零钱兑换 & 单词拆分(完全背包 + 字符串 DP)
算法
pearlthriving11 分钟前
c++当中的泛型思想以及c++11部分新特性
java·开发语言·c++
疯狂打码的少年18 分钟前
有序线性表删除一个元素:顺序存储 vs 单链表,平均要移动多少个元素?
数据结构·算法·链表
y = xⁿ33 分钟前
20天速通LeetCode day07:前缀和
数据结构·算法·leetcode
t***5441 小时前
Dev-C++中哪些选项可以设置
开发语言·c++
载数而行5201 小时前
算法集训1:模拟,枚举,错误分析,前缀和,差分
算法
hehelm1 小时前
vector模拟实现
前端·javascript·算法
2301_803554522 小时前
C++ 并发核心:std::promise、std::future、std::async 超详细全解
开发语言·c++
EverestVIP2 小时前
C++ 成员函数的指针
c++
俺不要写代码2 小时前
线程启动、结束,创建线程多法、join,detach,线程的移动语义
服务器·开发语言·网络·c++