In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about the role of the sort package in Golang, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
1. Sort.Sort ()
The function is defined as follows
Func Sort (data Interface) {n: = data.Len () quickSort (data, 0, n, maxDepth (n))}
The quickSort method is called in the Sort function, which is the specific implementation of the sorting algorithm. The core strategy is to adjust different sorting algorithms according to the amount of data to be sorted. This part is not included in the analysis of this article.
For package users, it is important to note that the input parameter of Sort is the Interface interface. What is this Interface? The following is its definition in sort.go.
Type Interface interface {/ / Len is the number of elements in the collection. Len () int / / Less reports whether the element with / / index i should sort before the element with index j. Less (I, j int) bool / / Swap swaps the elements with indexes i and j. Swap (I, j int)}
It can be seen that Interface is an interface type (interface), and the functional methods that need to be implemented are: Len, Less and Swap. What does that mean?
We know that the interface implementation in go is implicit, and as long as the object implements the methods defined by the interface, the interface can be implemented. Therefore, this approach is a non-intrusive implementation.
Then, if you need an object to be able to call the Sort method, just implement its parameter Interface interface.
In the Sort package, some object types have been implemented to call Sort functions, including: [] int, [] float64, [] string. Take the [] int type as an example to see its code implementation.
Type IntSlice [] int / / encapsulates [] int type using IntSlice type / / IntSlice object implements Interface interface func (p IntSlice) Len () int {return len (p)} func (p IntSlice) Less (I, j int) bool {return p [I]
< p[j] }func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }...//由于Intslice对象实现了Interface接口,即可以作为参数调用Sort方法。func Ints(a []int) { Sort(IntSlice(a)) } 这就是sort包对外提供的Ints函数:当需要对[]int数组进行排序时,直接调用sort.Ints()。 package main import ( "fmt" "sort") func main() { a := []int{12,45,33,78,9,14} sort.Ints(a) fmt.Println(a) //[9 12 14 33 45 78]} sort.Float64()和sort.Strings()同理。 2. 自定义对象调用Sort() 思考:假如需要排序的是自定义对象,应该如何实现。 给定对象person,其包括两个属性: name string, age int。那么如何根据姓名或者age给person进行排序。完整示例如下。 package main import ( "fmt" "sort") type person struct { //定义对象person name string age int} type personSlice []person //给[]person绑定对象 // 实现sort包定义的Interface接口func (s personSlice) Len() int { return len(s)} func (s personSlice) Less(i, j int) bool { return s[i].age < s[j].age} func (s personSlice) Swap(i, j int) { s[i].age, s[j].age = s[j].age, s[i].age} func main() { p := personSlice{ person{ name: "mike", age: 13, }, person{ name: "jane", age: 12, }, person{ name: "peter", age: 14, }} sort.Sort(p) fmt.Println(p) // [{mike 12} {jane 13} {peter 14}]} 注意:并不是所有对象都能实现排序,前提是排序依赖的属性列是可比较的,如int,string等。 3. sort.Search() 函数原型 func Search(n int, f func(int) bool) int {} Serarch里面的算法细节本文不讨论,只关注如何实现调用。Search函数中n参数是待搜索对象集的长度,注意此对象集必须是已排序过的;f参数是一个匿名函数,实现规则见下文[]int例子。 同样的,sort包已为几个特定对象实现了调用函数,包括[]int,[]float64,[]string。以[]int为例。 // 输入已排序[]int类型a,和某item值x,返回其在[]int中的索引值。// 注:小于[]int最小值返回0,大于最大值,返回len(a)func SearchInts(a []int, x int) int { return Search(len(a), func(i int) bool { return a[i] >= x})}. / / returns the index value of x in IntSlice ([] int) / / Note: less than the minimum value of [] int returns 0, greater than the maximum value, and returns len (a) func (p IntSlice) Search (x int) int {return SearchInts (p, x)}.
Examples of use:
Package main
Import ("fmt"sort")
Func main () {a: = [] int {3) fmt.Println (a) / / [1 2 3 4 5] fmt.Println (sort.SearchInts (a)) / / 4 fmt.Println (sort.SearchInts (a)) / / 5 fmt.Println (sort.IntSlice (a). Search (5) / / 4}
4. Custom object calls Search
It is also a person object, how to implement it if you want to find the subscript in the sorted person collection (personSlice) according to age. The sample code is as follows.
/ / call the sort.Search function Construct PersonSlice's own Search method func (s personSlice) Search (age int) int {return sort.Search (len (s), func (I int) bool {return s.age > = age})} func main () {p: = personSlice {person {name: "mike", age: 13,}, person {name: "jane", age: 12,}, person {name: "peter" Age: 14,} sort.Sort (p) fmt.Println (p) / [{mike 12} {jane 13} {peter 14}] fmt.Println (p.Search (13)) / / 1}
5. Other functions
Of course, there are other functions exposed to users in the sort package, such as: sort.IsSorted () is used to determine whether objects are ordered; sort.Stable () provides stable sorting, that is, when the element type is equal, the original relative position is retained; sort.Reverse () provides object collection element inversion, and so on. With the understanding of sort.Sort () and sort.Search (), these functions are similar calls or implementations.
These are the functions of the sort package in Golang. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.