對有序數列進行二分查找
尚硅谷Golang課
//對有序數列進行二分查找
var arr1 = [...]int{5, 9, 6, 8, 7, 3, 4, 2, 1, 0}

func bubble(x []int) {
	for j := 1; j < len(x); j++ {
		for i := 0; i < len(x)-1; i++ {
			if x[i] > x[i+1] {
				x[i], x[i+1] = x[i+1], x[i]
			}
		}
	}
}
func bi(x int, s []int, left int, right int) {
	middle := (right + left) / 2
	if left > right {
		fmt.Println("找不到")
		return
	}
	if x < s[middle] {
		//在左邊
		bi(x, s, left, middle-1)
	} else if x > s[middle] {
		//在右邊
		bi(x, s, middle+1, right)
	} else {
		fmt.Println("找到下標=", middle)
	}

}
func main() {
	s1 := arr1[:]
	bubble(s1)
	fmt.Println(s1)
	bi(9, s1, 0, len(s1)-1)
}

上次修改於 2021-08-01

此篇文章的評論功能已經停用。