我知道 Go 有一个sort包含搜索功能的包,但这是出于教育目的。我一直在尝试在 Go 中实现二进制搜索算法,但我一直无法让它工作。
这是我的代码:
package main
import "fmt"
func BinarySearch(data []int, target int, low int, high int) (index int, found bool) {
mid := (high + low) / 2
if low > high {
index = -1
found = false
} else {
if target < data[mid] {
BinarySearch(data, target, low, mid - 1)
} else if target > data[mid] {
BinarySearch(data, target, mid + 1, high)
} else if target == data[mid] {
index = mid
found = true
} else {
index = -1
found = false
}
}
return
}
func main() {
data := []int {2, 4, 6, 8, 9, 11, 12, 24, 36, 37, 39, 41, 54, 55, 56,}
index, found := BinarySearch(data, 8, 0, len(data) - 1)
fmt.Println(index, found)
}
它总是打印0 false. 为什么?
MM们
慕少森
qq_花开花谢_0
相关分类