Golang二分查找

注意: 二分查找只适用于有序序列

``````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("输入查找的值: ")
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!")
}
}
``````

结果

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

注意: 二分查找只适用于有序序列

``````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("输入查找的值: ")
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!")
}
}
``````