--- comments: true --- # 10.2. 二分查找 「二分查找 Binary Search」利用数据的有序性,通过每轮缩小一半搜索区间来查找目标元素。 使用二分查找有两个前置条件: - **要求输入数据是有序的**,这样才能通过判断大小关系来排除一半的搜索区间; - **二分查找仅适用于数组**,而在链表中使用效率很低,因为其在循环中需要跳跃式(非连续地)访问元素。 ## 10.2.1. 算法实现 给定一个长度为 $n$ 的排序数组 `nums` ,元素从小到大排列。数组的索引取值范围为 $$ 0, 1, 2, \cdots, n-1 $$ 使用「区间」来表示这个取值范围的方法主要有两种: 1. **双闭区间 $[0, n-1]$** ,即两个边界都包含自身;此方法下,区间 $[0, 0]$ 仍包含一个元素; 2. **左闭右开 $[0, n)$** ,即左边界包含自身、右边界不包含自身;此方法下,区间 $[0, 0)$ 为空; ### “双闭区间”实现 首先,我们先采用“双闭区间”的表示,在数组 `nums` 中查找目标元素 `target` 的对应索引。 === "Step 1" ![binary_search_step1](binary_search.assets/binary_search_step1.png) === "Step 2" ![binary_search_step2](binary_search.assets/binary_search_step2.png) === "Step 3" ![binary_search_step3](binary_search.assets/binary_search_step3.png) === "Step 4" ![binary_search_step4](binary_search.assets/binary_search_step4.png) === "Step 5" ![binary_search_step5](binary_search.assets/binary_search_step5.png) === "Step 6" ![binary_search_step6](binary_search.assets/binary_search_step6.png) === "Step 7" ![binary_search_step7](binary_search.assets/binary_search_step7.png) 二分查找“双闭区间”表示下的代码如下所示。 === "Java" ```java title="binary_search.java" [class]{binary_search}-[func]{binarySearch} ``` === "C++" ```cpp title="binary_search.cpp" [class]{}-[func]{binarySearch} ``` === "Python" ```python title="binary_search.py" [class]{}-[func]{binary_search} ``` === "Go" ```go title="binary_search.go" [class]{}-[func]{binarySearch} ``` === "JavaScript" ```javascript title="binary_search.js" [class]{}-[func]{binarySearch} ``` === "TypeScript" ```typescript title="binary_search.ts" [class]{}-[func]{binarySearch} ``` === "C" ```c title="binary_search.c" ``` === "C#" ```csharp title="binary_search.cs" [class]{binary_search}-[func]{binarySearch} ``` === "Swift" ```swift title="binary_search.swift" [class]{}-[func]{binarySearch} ``` === "Zig" ```zig title="binary_search.zig" [class]{}-[func]{binarySearch} ``` ### “左闭右开”实现 当然,我们也可以使用“左闭右开”的表示方法,写出相同功能的二分查找代码。 === "Java" ```java title="binary_search.java" [class]{binary_search}-[func]{binarySearch1} ``` === "C++" ```cpp title="binary_search.cpp" [class]{}-[func]{binarySearch1} ``` === "Python" ```python title="binary_search.py" [class]{}-[func]{binary_search1} ``` === "Go" ```go title="binary_search.go" [class]{}-[func]{binarySearch1} ``` === "JavaScript" ```javascript title="binary_search.js" [class]{}-[func]{binarySearch1} ``` === "TypeScript" ```typescript title="binary_search.ts" [class]{}-[func]{binarySearch1} ``` === "C" ```c title="binary_search.c" ``` === "C#" ```csharp title="binary_search.cs" [class]{binary_search}-[func]{binarySearch1} ``` === "Swift" ```swift title="binary_search.swift" [class]{}-[func]{binarySearch1} ``` === "Zig" ```zig title="binary_search.zig" [class]{}-[func]{binarySearch1} ``` ### 两种表示对比 对比下来,两种表示的代码写法有以下不同点: