forked from go/golangs_learn
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.
748 B
748 B
二分查找
- 介绍
- 关键字
- 开始为左,截止为右.
- 候选区(左<右)
- 左>右,不存在后选取区
- 关键字
- 原理
- 前提 必须进行排序
- 代码
func main() {
list := []int{1, 2, 3, 45, 13, 16, 7}
fmt.Println(BinaryQuery(list, 13))
}
// BinaryQuery 二分查找的实现,如果查找成功返回索引;否则返回-1
func BinaryQuery(list []int, target int) int {
// 定义并初始化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;
}
}
return -1
}