You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
748 B

# 二分查找
* **介绍**
* 关键字
* 开始为左,截止为右.
* **候选区**(左<)
* 左>右,不存在后选取区
* **原理**
3 years ago
* **前提** 必须进行排序
* **代码**
3 years ago
```go
func main() {
list := []int{1, 2, 3, 45, 13, 16, 7}
fmt.Println(BinaryQuery(list, 13))
}
3 years ago
// BinaryQuery 二分查找的实现,如果查找成功返回索引;否则返回-1
func BinaryQuery(list []int, target int) int {
3 years ago
// 定义并初始化low和high,声明mid
low, high := 0, len(list)-1
// 前提必须进行排序
sort.Ints(list)
for low <= high {
mid := (low + high) / 2
if list[mid] == target {
return mid
}else if list[mid] > target {
high = mid - 1
}else {
low = mid + 1;
}
}
3 years ago
return -1
}
```