【golang/方法记录】有序列表的简易实现

说在前面

  • go version:go1.14.1 windows/amd64

实现

  • 借助golang中的sort包可以方便的使用二分查找。
    func Search(n int, f func(int) bool) int {
    	// Define f(-1) == false and f(n) == true.
    	// Invariant: f(i-1) == false, f(j) == true.
    	i, j := 0, n
    	for i < j {
    		h := int(uint(i+j) >> 1) // avoid overflow when computing h
    		// i ≤ h < j
    		if !f(h) {
    			i = h + 1 // preserves f(i-1) == false
    		} else {
    			j = h // preserves f(j) == true
    		}
    	}
    	// i == j, f(i-1) == false, and f(j) (= f(i)) == true  =>  answer is i.
    	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)
    	// [1 2 12 102 112 142 14542]
    }
    
  • 其他的可以通过定义结构体,并使用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)
    	}
    	
    	// {2 kiss}
    	// {12 one}
    	// {12 ha}
    	// {112 see}
    	// {1432 ta}
    	// {1452 sight}
    	// {13332 peer}
    }
    
  • 其他还可以进一步进行封装,例如写成package

你可能感兴趣的:(Go,golang,开发语言,后端)