0%

二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func main() {
arr := []int{0, 1, 2, 3, 4, 5, 6}
fmt.Println(BinarySearch(arr, 5))
}
func BinarySearch(s []int, k int) int {
lo, hi := 0, len(s)-1
for lo <= hi {
m := (lo + hi) >> 1
if s[m] < k {
lo = m + 1
} else if s[m] > k {
hi = m - 1
} else {
return m
}
}
return -1
}