【亿码酷站-编程开发教程】收集全网优质教程及源码资源!

全网优质软件开发、平面设计等教程及精品源码资源一站可得,www.ymkuzhan.com!

下面由
golang教程栏目给大家介绍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)}

这个设计太妙了有没有,想想我们学过的排序,都要序列长度,比大小,交换元素。
那对上述的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 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之排序使用
—–文章转载自PHP中文网如有侵权请联系admin#tyuanma.cn删除

关于redis数据库数量配置、切换及指定数据库

云服务器推荐