算法基础 - 二分查找

文章目录

二分查找算法通常应用于已排序的数组。以下是一个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函数并输出结果。

相关推荐
hetao173383712 分钟前
2026-08-27~29 hetao1733837 的刷题记录
c++·算法
chen<>25 分钟前
C++ 六种 memory_order:从原子性到线程间可见性.md
java·linux·开发语言·c++
云淡风轻~窗明几净29 分钟前
宇宙管理学猜想
算法·图论
会周易的程序员35 分钟前
企业私有 AI 算力服务器架构设计:异构四节点 + QUIC 微服务
运维·服务器·c++·人工智能·微服务·架构
春风解人意36 分钟前
从零开始学习嵌入式P28----线程
c语言·学习·算法
m0_7345717638 分钟前
深入理解C++ 类型转换<三>const_cast
开发语言·c++
luj_176838 分钟前
合法避税与投资评估实战指南
c语言·开发语言·网络·经验分享·算法
库玛西1 小时前
Linux网络编程:HTTP/HTTPS协议核心技术全解析
linux·运维·服务器·网络·c++·http·https
Bruce_Liuxiaowei1 小时前
驴滑块拼图游戏:从19世纪的纸片谜题到数学博弈论
人工智能·算法
一直C1 小时前
Linux系统编程|信号进阶 + SystemV IPC(消息队列、共享内存)
linux·c语言·开发语言·算法·青少年编程·vim