Skip to content

Commit ee93cd1

Browse files
authored
Update binary_search.md
1 parent bc2561f commit ee93cd1

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

docs/chapter_searching/binary_search.md

+18-1
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,24 @@ $$
220220
=== "Go"
221221

222222
```go title="binary_search.go"
223-
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+
}
224241
```
225242

226243
=== "JavaScript"

0 commit comments

Comments
 (0)