package main import ( "fmt" "sort" ) 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 fmt.Println(low, high, mid) if list[mid] == target { return mid } else if list[mid] > target { high = mid - 1 } else { low = mid + 1 } } return -1 }