二分查找
package main
import "fmt"
// 二分查找
func BFind(slice []int, leftIndex int, rightIndex int, findValue int) {
if leftIndex > rightIndex {
fmt.Println("找不到该数值")
return
}
centIndex := (leftIndex + rightIndex) / 2
if slice[centIndex] < findValue {
BFind(slice, centIndex+1, rightIndex, findValue)
} else if slice[centIndex] > findValue {
BFind(slice, leftIndex, centIndex-1, findValue)
} else {
fmt.Printf("找到这个数: %d,下标为%d", findValue, centIndex)
}
}
func main() {
// 定义切片
var slice = []int{9, 11, 12, 21, 22, 69}
BFind(slice, 0, len(slice), 69)
}
输出结果
找到这个数: 69,下标为5
文章评论