a:如果 arr[middle] > FindVal,那麼就向 LeftIndex ~ (midlle-1) 區間找
b:如果 arr[middle] < FindVal,那麼就向 middle+1 ~ RightIndex 區間找
c:如果 arr[middle] == FindVal,那麼直接返回
left = 1, right = 18; mid = (1+18)/2 = 9; 51 > 30
left = 1, right = mid - 1 = 8; mid = (1+8)/2 = 4; 15 < 30
left = mid + 1 = 5, right = 8; mid = (5+8)/2 = 6; 30 = 30 查詢完畢
package main import ( "fmt" ) //二分查詢函數 //假設有序陣列的順序是從小到大(很關鍵,決定左右方向) func BinaryFind(arr *[]int, leftIndex int, rightIndex int, findVal int) { //判斷 leftIndex是否大於rightIndex if leftIndex > rightIndex { fmt.Println("找不到") return } //先找到 中間的下標 middle := (leftIndex + rightIndex) / 2 if (*arr)[middle] > findVal { //要查詢的數,範圍應該在 leftIndex 到 middle+1 BinaryFind(arr, leftIndex, middle-1, findVal) } else if (*arr)[middle] < findVal { //要查詢的數,範圍應該在 middle+1 到 rightIndex BinaryFind(arr, middle+1, rightIndex, findVal) } else { fmt.Printf("找到了,下標為:%v n", middle) } } func main() { //定義一個陣列 arr := []int{1, 2, 5, 7, 15, 25, 30, 36, 39, 51, 67, 78, 80, 82, 85, 91, 92, 97} BinaryFind(&arr, 0, len(arr) - 1, 30) fmt.Println("main arr=",arr) }執行結果如下所示:
D:code>go run main.go
找到了,下標為:6
main arr= [1 2 5 7 15 25 30 36 39 51 67 78 80 82 85 91 92 97]