算法基础 - 二分查找

文章目录

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

相关推荐
小小龙学IT3 分钟前
zstd(Zstandard)开源压缩库实战指南:让数据又快又小
c++·开源
小小龙学IT41 分钟前
GLM 开源图形学数学库深度解析:从向量、矩阵到四元数的完整实战
c++·矩阵·开源·mfc
dtq04241 小时前
数据结构 - 线性表 - 单链表
数据结构
Severus_black1 小时前
【C++初阶】类和对象(中)
c++
万法若空1 小时前
对数恒等式
人工智能·算法·机器学习
AI小码1 小时前
如何让AI帮你构建项目?七级方法
人工智能·算法·计算机·ai·程序员·大模型·编程
1000世界小札1 小时前
排序算法全景总结:从 O(n²) 到 O(n log n),再到线性时间(附完整对比与选型指南)
数据结构·算法·排序算法
一直C2 小时前
【Linux应用编程】深入理解Linux多任务机制:进程原理、状态转换与进程控制实战
linux·开发语言·算法·ubuntu·vim·visual studio code
qz5zwangzihan12 小时前
AtCoder高频英文词汇短语
c++·atcoder·高频词
码匠许师傅2 小时前
【C++ 面试真题】聊聊 C++ 的类型特征( type_traits)
java·c++·面试