Golang in the Sort Pack sort.search () use tutorial

Source: Internet
Author: User

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}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.