关于golang之排序使用

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

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

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

type User struct { 	Name  string 	Score 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)}

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

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 Users	const N = 6  	for i := 0; i < N; i++ { 		us = append(us, User{ 			Name:  "user" + strconv.Itoa(i), 			Score: rand.Intn(N * N), 		}) 	}  	fmt.Printf("%v\n", us) 	sort.Sort(us) 	fmt.Printf("%v\n", us)}

可能的输出为:

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

不过一般我们积分这种东西都是从大到小排序的,只需将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] = tmp	return hi}

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

总结:

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

欢迎补充指正!

以上就是关于golang之排序使用的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: golang
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:关于Go语言的http/2服务器功能及客户端使用方法

相关资讯