栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

关于golang之排序使用

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于golang之排序使用

下面由golang教程栏目给大家介绍golang之排序使用,希望对需要的朋友有所帮助!

golang标准库实现了许多常用的排序方法,比如对整数序列排序:sort.Ints(),
那么如果对自定义的数据结构排序怎么做呢?
比如对一个用户列表,按他们的积分排序:

首先定义数据结构,为了能清楚说明问题,只给两个字段。

type User struct {Name  stringScore int}type Users []User

golang中想要自定义排序,自己的结构要实现三个方法:

// 摘自: $GOROOT/src/sort/sort.gotype 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)}

这个设计太妙了有没有,想想我们学过的排序,都要序列长度,比大小,交换元素。
那对上述的Users,也就是用户列表如何使用golang的排序呢?

先按它说的,实现这三个方法:

func (us Users) Len() int {return len(us)}func (us Users) Less(i, j int) bool {return us[i].Score < us[j].Score}func (us Users) Swap(i, j int) {us[i], us[j] = us[j], us[i]}

然后就能排序了:

func main() {var us Usersconst N = 6for i := 0; i < N; i++ {us = append(us, User{Name:  "user" + strconv.Itoa(i),Score: rand.Intn(N * N),})}fmt.Printf("%vn", us)sort.Sort(us)fmt.Printf("%vn", us)}

可能的输出为:

[{user0 5} {user1 15} {user2 11} {user3 11} {user4 13} {user5 6}]
[{user0 5} {user5 6} {user2 11} {user3 11} {user4 13} {user1 15}]

可以看到,分数从小到大排列了。

不过一般我们积分这种东西都是从大到小排序的,只需将
sort.Sort(us)改成sort.Sort(sort.Reverse(us))就行。

确实很方便。

当然,如果出于特殊需要,系统提供的排序不能满足我们的需要,
还是可以自己实现排序的, 比如针对上述,自己来排序(从小到大):

func myqsort(us []User, lo, hi int) {if lo < hi {pivot := partition(us, lo, hi)myqsort(us, lo, pivot-1)myqsort(us, pivot+1, hi)}}func partition(us []User, lo, hi int) int {tmp := us[lo]for lo < hi {for lo < hi && us[hi].Score >= tmp.Score {hi--}us[lo] = us[hi]for lo < hi && us[lo].Score <= tmp.Score {lo++}us[hi] = us[lo]}us[lo] = tmpreturn hi}

一个简单的快速排序,调用时只需要myqsort(us)就可以 了。

总结:

自定义序列要实现Less, Swap, Len三个方法 才行

欢迎补充指正!

以上就是关于golang之排序使用的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/793952.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号