算法基础 - 二分查找

文章目录

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

相关推荐
凌冰_6 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi7 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜7 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄9 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
无忧.芙桃11 小时前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
郝学胜-神的一滴13 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
AvocadoZeroOneOI14 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
cjz389916 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
whitelbwwww16 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
console.log('npc')18 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习