41 lines
692 B
Go
41 lines
692 B
Go
/*
|
|
* @Description: 二分查找
|
|
* @Version: 2.0
|
|
* @Autor: zhuyijun
|
|
* @Date: 2021-03-29 09:08:50
|
|
* @LastEditors: zhuyijun
|
|
* @LastEditTime: 2021-03-29 17:35:47
|
|
*/
|
|
package main
|
|
|
|
import "fmt"
|
|
|
|
/**
|
|
二分查找算法
|
|
*/
|
|
func BinarySearch(key int, a []int) int {
|
|
lo := 0
|
|
hi := len(a) - 1
|
|
for lo < hi {
|
|
mid := lo + (hi-lo)/2
|
|
if key < a[mid] {
|
|
hi = mid - 1
|
|
} else if key > a[mid] {
|
|
lo = mid + 1
|
|
} else {
|
|
return mid
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
func main() {
|
|
var a = []int{0, 2, 4, 7, 9, 11, 45, 67, 99, 100}
|
|
var i int = 2
|
|
key := BinarySearch(i, a)
|
|
if key > 0 {
|
|
fmt.Printf("已查到:%d,位置在:%d \n", i, key+1)
|
|
} else {
|
|
fmt.Printf("没有查到a数组中有%d", i)
|
|
}
|
|
}
|