算法基础 - 二分查找

文章目录

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

相关推荐
感哥9 小时前
C++ 多态
c++
沐怡旸16 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
NAGNIP16 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队17 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
River41619 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥21 小时前
C++ std::set
c++
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法