Go-二分查找

查找

1.顺序查找 (一个一个的比对查找)

2.二分查找

先排序,每次找中间(左右下标相加除2)值比较,

大于mid就在mid+1:end区间,然后在mid+1:end再找mid值比较。

一直递归下去,start值在增长,end值在减少,当start的值大于end值时,

就意味着不包含此数,结束递归

func main() {

	// s := []string{"一天", "二天", "三天"}
	// d := findbyorder(&s, "g天")
	// fmt.Println(d)
	s := []int{11, 22, 33, 44, 55, 66}
	binaryfind(&s, 444, 0, 5)

}

func findbyorder(ds *[]string, s string) string {
	ret := "N"
	for _, va := range *ds {
		if va == s {
			ret = "Y"
			break
		}
	}
	return ret
}

func binaryfind(ds *[]int, s int, startidx int, endidx int) {

	if startidx > endidx {
		fmt.Println("不存在")
		return
	}
	mididx := (startidx + endidx) / 2
	if s > (*ds)[mididx] {
		binaryfind(ds, s, mididx+1, endidx)

	} else if s < (*ds)[mididx] {
		binaryfind(ds, s, startidx, mididx-1)
	} else {
		fmt.Println("下标:", mididx)
	}
}
原文地址:https://www.cnblogs.com/JinweiChang/p/14160657.html