Skip to content

二分查找

前提

  1. 目标函数单调性(单调递增或者递减)
  2. 存在上下界(bounded)
  3. 能够通过索引访问(index accessible)

模板

java
int left = 0, right = arr.length - 1;
while (left <= right) {
    int min = (right - left) / 2 + left;
    if (arr[min] == target) {
        break of return result;
    } else if (arr[min] < target) {
        left = min + 1;
    } else {
        right = min + 1;
    }
}