gpt4 book ai didi

algorithm - 进行递归二分查找

转载 作者:IT王子 更新时间:2023-10-29 02:26:36 25 4
gpt4 key购买 nike

我知道 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。为什么?

最佳答案

二分查找的逻辑是合理的。唯一的问题是您忘记了将每次递归调用的结果分配给 indexfound

目前你有这些递归调用:

BinarySearch(data, target, low, mid - 1)
//...
BinarySearch(data, target, mid + 1, high)

您只需分配结果:

index, found = BinarySearch(data, target, low, mid - 1)
//...
index, found = BinarySearch(data, target, mid + 1, high)

关于algorithm - 进行递归二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32664475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com