算法基础 - 二分查找

文章目录

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

相关推荐
Shaoshing3 分钟前
LeetCode100 155.最小栈
java·数据结构·算法
秋天的怀念_David41 分钟前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
纪念 2291 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法
li星野1 小时前
C++/Qt 开发避坑与重构原则清单 (速记版)
c++·qt·重构
西西弗Sisyphus1 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 函数指针详解(3)
c++
echoliuy1 小时前
二叉树—二叉搜索树 前序 中序 后序
算法·深度优先
怕浪猫1 小时前
机器人是当下薪酬最高却几乎没人学的技能:一份 6 个月从 0 到上手的学习路线
算法·架构·github
杜 硕1 小时前
从零开始的C++生活——第十六讲
开发语言·数据结构·c++·生活
MobotStone2 小时前
打造高性价比 AI 应用:选对模型、用好缓存、持续测试
人工智能·算法