package main
import (
"fmt"
)
//在有序的切片中查找指定的值。每次都需要从中间位置开始,
//如果索引对应的值和目标值一致就返回,如果中间位置的值大于目标值那下次就需要从0~(索引-1)寻找
//如果中间位置的值小于目标值那下次就需要从(索引+1)~最后 寻找
//注意 切片内的元素必须是升序排好序的
func FindValue(target int, slice []int) int {
low := 0
hight := len(slice) - 1
step := 0
for {
step++
fmt.Printf("共查找了%d次\n", step)
searchIndex := (hight + low) / 2
middleValue := slice[searchIndex]
if low <= hight {
if middleValue > target {
hight = searchIndex - 1
} else if middleValue < target {
low = searchIndex + 1
} else {
fmt.Printf("索引是%d\n 值是%d\n", searchIndex, middleValue)
return searchIndex
}
}
}
}
func main() {
list := make([]int, 1_000_000)
for i := 0; i < 1_000_000; i++ {
list = append(list, i+1)
}
FindValue(67, list)
FindValue(10005, list)
fmt.Println(fmt.Println())
//FindValue(target,slice)