本页目录

二分查找(Binary Search)

二分查找每次取区间中点元素与目标进行比较,无论结果如何,都能将搜索区间缩小一半,从而在 O(log n) 时间内完成查找。

前提:数组必须有序且支持随机访问(顺序存储结构)。

查找过程

每次取区间 [lo, hi] 的中点 mid = (lo + hi) / 2 进行比较:

过程模拟

以有序数组 [1, 3, 5, 7, 9, 11, 13]、目标 target = 11 为例:

二分查找步骤 1
步骤 1 / 2

左右边界与插入点

当数组中存在重复元素,或需要确定插入位置时,需要使用二分的边界变体:

算法特性

Baseline 任务:二分查找

任务内容

完成 ordered_search.cpp,实现以下函数:

  1. 基础二分查找 int BinarySearch(vector<int>& nums, int target)
    • 在有序表中查找目标关键字,返回下标或 -1
  2. 左边界查找 int BinarySearchLeftBound(vector<int>& nums, int target)
    • 返回 target 首次出现的下标
  3. 右边界查找 int BinarySearchRightBound(vector<int>& nums, int target)
    • 返回 target 末次出现的下标
  4. 插入位置查找 int BinarySearchInsertionPoint(vector<int>& nums, int target)
    • 返回 target 应插入的位置,使数组保持有序

文件结构

验证方式