> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/algorithms/binary-search.md).

# 二分查找与二分答案

### 二分查找

在**有序数组**中快速查找目标值，每次比较中间元素，排除一半。时间复杂度 O(log n)。

```cpp
int binarySearch(int a[], int n, int x) {
    int l = 0, r = n - 1;
    while (l <= r) {
        int mid = (l + r) / 2;
        if (a[mid] == x) return mid;
        else if (a[mid] < x) l = mid + 1;
        else r = mid - 1;
    }
    return -1;  // 未找到
}
```

### 二分答案（二分枚举法）

当答案具有**单调性**（越大越容易/越难满足）时，二分枚举答案，再把答案代入判断是否可行。

模板（求满足条件的最大值）：

```cpp
int l = 0, r = 1e9, ans = 0;
while (l <= r) {
    int mid = l + (r - l) / 2;
    if (check(mid)) { ans = mid; l = mid + 1; }  // 可行，尝试更大
    else r = mid - 1;
}
cout << ans;
```

### 经典场景

* 最小值最大 / 最大值最小
* 分割问题、砍树问题、跳石头问题

### 要点

* 二分的前提是**单调有序**。
* `mid` 写法 `l + (r - l) / 2` 可防溢出。
* 注意边界收缩方向与最终答案的取值。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/algorithms/binary-search.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
