算法基础 - 二分查找

文章目录

二分查找算法通常应用于已排序的数组。以下是一个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++之基础A(二维数组)第四课
开发语言·c++
君义_noip9 小时前
信息学奥赛一本通 1615:【例 1】序列的第 k 个数
c++·算法·信息学奥赛·csp-s
ホロHoro9 小时前
数据结构非线性部分(1)
java·数据结构·算法
Blossom.1189 小时前
大模型推理优化实战:连续批处理与PagedAttention性能提升300%
大数据·人工智能·python·神经网络·算法·机器学习·php
AA陈超9 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-19.发送鼠标光标数据
c++·笔记·学习·游戏·ue5·虚幻引擎
沉下去,苦磨练!9 小时前
实现二维数组反转
java·数据结构·算法
bybitq9 小时前
Leetcode-3780-Python
python·算法·leetcode
如何原谅奋力过但无声9 小时前
【力扣-Python-75】颜色分类(middle)
python·算法·leetcode
玖剹9 小时前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
红豆诗人9 小时前
数据结构初阶知识--单链表
c语言·数据结构