说在前面
- go version:go1.14.1 windows/amd64
实现
- 借助
golang 中的sort 包可以方便的使用二分查找。func Search(n int, f func(int) bool) int {
i, j := 0, n
for i < j {
h := int(uint(i+j) >> 1)
if !f(h) {
i = h + 1
} else {
j = h
}
}
return i
}
- 借助二分查找可以方便的实现有序列表。
代码
-
例如有序的uint64 切片 func SeachUint64List(arr []uint64, x uint64) int {
return sort.Search(len(arr), func(i int) bool {
return arr[i] >= x
})
}
func InsertOrderedUint64List(arr []uint64, x uint64) []uint64 {
i := SeachUint64List(arr, x)
arr = append(arr, 0)
copy(arr[i+1:], arr[i:])
arr[i] = x
return arr
}
func main() {
var arr []uint64
arr = InsertOrderedUint64List(arr, 12)
arr = InsertOrderedUint64List(arr, 2)
arr = InsertOrderedUint64List(arr, 102)
arr = InsertOrderedUint64List(arr, 1)
arr = InsertOrderedUint64List(arr, 14542)
arr = InsertOrderedUint64List(arr, 112)
arr = InsertOrderedUint64List(arr, 142)
fmt.Println(arr)
}
-
其他的可以通过定义结构体,并使用Key 进行排序,例如 type Node struct {
Key uint64
Value string
}
func SeachNodeList(arr []*Node, x uint64) int {
return sort.Search(len(arr), func(i int) bool {
return arr[i].Key >= x
})
}
func InsertOrderedNodeList(arr []*Node, x *Node) []*Node {
if x == nil {
return arr
}
i := SeachNodeList(arr, x.Key)
arr = append(arr, &Node{})
copy(arr[i+1:], arr[i:])
arr[i] = x
return arr
}
func main() {
var arr []*Node
arr = InsertOrderedNodeList(arr, &Node{Key: 12, Value: "ha"})
arr = InsertOrderedNodeList(arr, &Node{Key: 1432, Value: "ta"})
arr = InsertOrderedNodeList(arr, &Node{Key: 112, Value: "see"})
arr = InsertOrderedNodeList(arr, &Node{Key: 1452, Value: "sight"})
arr = InsertOrderedNodeList(arr, &Node{Key: 13332, Value: "peer"})
arr = InsertOrderedNodeList(arr, &Node{Key: 12, Value: "one"})
arr = InsertOrderedNodeList(arr, &Node{Key: 2, Value: "kiss"})
for _, node := range arr {
fmt.Println(*node)
}
}
-
其他还可以进一步进行封装,例如写成package
|