算法基础 - 二分查找

文章目录

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

相关推荐
Lhan.zzZ6 小时前
笔记_2026.4.28_004
c++·ide·笔记·qt
wuminyu8 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
木喃的井盖9 小时前
无锁队列细节
c++·工程
王老师青少年编程9 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
MediaTea9 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z9 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue9 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅10 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
KuaCpp10 小时前
C++面向对象(速过复习版)
开发语言·c++
MATLAB代码顾问11 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法