注意: 二分查找只适用于有序序列
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
arr := []int{3, 4, 7, 9, 13, 45, 67, 89, 100, 180}
// 排序前的数值
fmt.Println("数组中的数据: ")
fmt.Println(arr)
fmt.Print("输入查找的值: ")
reader := bufio.NewReader(os.Stdin)
str, _ := reader.ReadString('\n')
str = strings.Replace(str, " ", "", -1)
str = strings.Replace(str, "\n", "", -1)
m, _ := strconv.Atoi(str)
low, k := 0, 0
high := len(arr) - 1
for {
if low > high {
break
}
mid := (low + high) / 2
if m > arr[mid] {
low = mid + 1
} else if m < arr[mid] {
high = mid - 1
} else {
k = mid
break
}
}
if k > 0 {
fmt.Printf("m = %d, k = %d \n", m, k)
} else {
fmt.Println("Not be found!")
}
}
结果
有疑问加站长微信联系(非本文作者)