package main
import "fmt"
func main() {
nums1 := []int{0, 1, 2, 3, 4, 5, 6}
index := binarySearch(nums1, 6, 0, len(nums1)-1)
fmt.Println(index)
}
// 二分查找
func binarySearch(arr []int, target int, l int, r int) int {
midIndex := (l + r) / 2
if target < arr[midIndex] {
r = midIndex - 1
return binarySearch(arr, target, l, r)
} else if target > arr[midIndex] {
l = midIndex + 1
return binarySearch(arr, target, l, r)
} else if target == arr[midIndex] {
return midIndex
}
return -1
}
二分查找(go)
最新推荐文章于 2024-05-15 16:18:29 发布