题目
利用go语言写一个二分查找的算法,查询0-9999个数中的某一个数,打印查找的次数
Go语言实现
主函数
import(
"fmt"
)
func main() {
var array [10000]int
for i := 0; i < 10000; i++ {
array[i] = i
}
var result1,result2,result3,result4,result5 = Search(&array,15)
fmt.Println(result1,result2,result3,result4,result5)
}
二分查找
//调用二分查找返回结果
func Search(data *[10000]int,value int) (int ,string,int,string,int) {
height := len(data) - 1
var index,count = rankSearch2(data,value,height,0)
return value ,"的查找次数:" ,count,"索引号:",index
}
//二分查找(递归)
var count = 0
func rankSearch(data *[10000]int, value int,height int,low int) (int,int) {
count ++
key := (height+low) / 2
if value == data[height] {
return height,count
}
if value == data[low] {
return low,count
}
if value == data[key] {
return key,count
}
if value > key {
low = key
return rankSearch(data ,value,height - 1,low + 1)
}
if value < key {
height = key
return rankSearch(data,value,height-1,low + 1)
}
return 0,0
}