一、条件:一组数据要进行二分查找,那么这个要查找的元素是有序,并且是连续存放(数组)。这样才可以进行二分查找。在数据库主键查找,二分查找算法是底层算法原理。
二、下面用golang来实现二分算法
package main标签:二分,int,lookingFor,mid,golang,sortedArray,查找,low,var From: https://blog.51cto.com/wyf1226/5906906
import (
"fmt"
)
func main() {
var lookingFor int = 6
var sortedArray []int = []int{1, 3, 4, 6, 7, 9, 10, 11, 13, 14}
index := binarySearch(sortedArray, lookingFor)
fmt.Println("数组", sortedArray)
fmt.Println("要查找的索引", lookingFor)
if index >= 0 {
fmt.Println("找到索引:", index)
} else {
fmt.Println("没有找到数据!")
}
}
func binarySearch(sortedArray []int, lookingFor int) int {
var low int = 0
var high int = len(sortedArray) - 1
for low <= high {
//(high-low)/2向下取整
var mid int = low + (high-low)/2
//fmt.Printf("%f", mid)
var midValue int = sortedArray[mid]
if midValue == lookingFor {
return mid
} else if midValue > lookingFor {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}