算法基础 - 二分查找

文章目录

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

相关推荐
Irissgwe几秒前
算法之二分查找
数据结构·c++·算法·二分查找
zh_xuan10 分钟前
c++ span的用法
开发语言·c++·span
亿牛云爬虫专家22 分钟前
代理IP质量评估:如何建立一套代理IP的多维度评分与淘汰算法?
tcp/ip·算法·爬虫代理·延迟·免费代理ip·连通率·时效
zzz_236825 分钟前
【Java实习面试算法冲刺】动态规划
java·算法·面试
小蒋学算法32 分钟前
算法-滑动窗口最大值
数据结构·算法
t-think33 分钟前
一起think C++:C++基础篇(一)—— namespace、IO、缺省参数与函数重载
c++
冷小鱼43 分钟前
AI Agent的核心算法:自主学习与反思(Self-Reflection / Critique)
人工智能·学习·算法·自主学习·self-reflection·critique·反思
持力行8 小时前
从C struct到C++中的class
c语言·c++
youtootech9 小时前
HarmonyOS《柚兔学伴》项目实战09-待办列表 UI——List+ForEach+滑动删除
数据结构·ui·华为·list·harmonyos
:-)10 小时前
算法-归并排序
java·开发语言·数据结构·算法·排序算法