Func Search (n int, f func (int) bool) int
Search uses dichotomy to find, and the search () method uses a "binary lookup" algorithm that searches for a specified slice [0:n] and returns the smallest I (0<=i<n) value that can make F (i) =true, and it assumes that f (i) =true, if F (i+ 1) =true, that is, for slices [0:n],i before the slice element will cause the F () function to return the elements after false,i and I will cause the F () function to return True. However, the Search () method returns N (instead of 1) when I cannot be found in the slice (at which point the slice element does not return the F () function to True) when F (i) =true i.
Search is often used to look for a value x, such as an array or a slice, indexed to I in a sorted, indexable data structure. In this case, the argument F, which is typically a closure, captures the value to be searched and how the data structure is indexed and sorted.
In order to find a value instead of a range of values, if slice is sorted in ascending order, then >= should be used in F func, and <= should be used if slice is sorted in descending order. Examples are as follows: Package main
Package Main import ("FMT" "sort") Func main () {a: = []int{1, 2, 3, 4, 5} b: = So Rt. Search (Len (a), func (i int) bool {return a[i] >=) fmt. Println (b)//5, not found, returns the length of a slice 5 instead of 1 c: = sort. Search (Len (a), func (i int) bool {return a[i] <= 3}) fmt. PRINTLN (c)//0, using the binary method to find, returns the index of the leftmost value that matches the condition, which is 0 d: = sort. Search (Len (a), func (i int) bool {return A[i] = = 3}) fmt. Println (d)//2}