# 二分查找 「二分查找 Binary Search」利用数据的有序性,通过每轮减少一半搜索范围来定位目标元素。 ## 算法实现 给定一个长度为 $n$ 的有序数组 `nums` ,元素按从小到大的顺序排列。数组索引的取值范围为: $$ 0, 1, 2, \cdots, n-1 $$ 我们通常使用以下两种方法来表示这个取值范围: 1. **双闭区间 $[0, n-1]$** ,即两个边界都包含自身;在此方法下,区间 $[0, 0]$ 仍包含 $1$ 个元素; 2. **左闭右开 $[0, n)$** ,即左边界包含自身、右边界不包含自身;在此方法下,区间 $[0, 0)$ 不包含元素; ### “双闭区间”实现 首先,我们采用“双闭区间”表示法,在数组 `nums` 中查找目标元素 `target` 的对应索引。 === "<1>" ![二分查找步骤](binary_search.assets/binary_search_step1.png) === "<2>" ![binary_search_step2](binary_search.assets/binary_search_step2.png) === "<3>" ![binary_search_step3](binary_search.assets/binary_search_step3.png) === "<4>" ![binary_search_step4](binary_search.assets/binary_search_step4.png) === "<5>" ![binary_search_step5](binary_search.assets/binary_search_step5.png) === "<6>" ![binary_search_step6](binary_search.assets/binary_search_step6.png) === "<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" [class]{}-[func]{binarySearch} ``` === "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" [class]{}-[func]{binarySearch1} ``` === "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} ``` ### 两种表示对比 对比这两种代码写法,我们可以发现以下不同点: