We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent bc2561f commit ee93cd1Copy full SHA for ee93cd1
docs/chapter_searching/binary_search.md
@@ -220,7 +220,24 @@ $$
220
=== "Go"
221
222
```go title="binary_search.go"
223
-
+ /* 二分查找(左闭右开) */
224
+ func binarySearch1(nums []int, target int) int {
225
+ // 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
226
+ i, j := 0, len(nums)
227
+ // 循环,当搜索区间为空时跳出(当 i = j 时为空)
228
+ for i < j {
229
+ m := (i + j) / 2 // 计算中点索引 m
230
+ if nums[m] < target { // 此情况说明 target 在区间 [m+1, j) 中
231
+ i = m + 1
232
+ } else if nums[m] > target { // 此情况说明 target 在区间 [i, m) 中
233
+ j = m
234
+ } else { // 找到目标元素,返回其索引
235
+ return m
236
+ }
237
238
+ // 未找到目标元素,返回 -1
239
+ return -1
240
241
```
242
243
=== "JavaScript"
0 commit comments