算法基础 - 二分查找

文章目录

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

相关推荐
小小小新人1212315 分钟前
C语言 ATM (4)
c语言·开发语言·算法
Azxcc039 分钟前
C++异步编程入门
开发语言·c++
吐泡泡_42 分钟前
C++(STL源码刨析/vector)
c++
你的冰西瓜43 分钟前
C++排序算法全解析(加强版)
c++·算法·排序算法
এ᭄画画的北北1 小时前
力扣-31.下一个排列
算法·leetcode
特立独行的猫a1 小时前
11款常用C++在线编译与运行平台推荐与对比
java·开发语言·c++
笑鸿的学习笔记1 小时前
qt-C++笔记之setCentralWidget的使用
c++·笔记·qt
绝无仅有2 小时前
企微审批对接错误与解决方案
后端·算法·架构
苏克贝塔3 小时前
Qt 图形视图框架3-事件处理与传播
c++·qt