golang之排序使用

版权声明:转载请注明出处,谢谢。 https://blog.csdn.net/butterfly5211314/article/details/83589945

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

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

type User struct {
	Name  string
	Score int
}

type Users []User

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

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

这个设计太妙了有没有,想想我们学过的排序,都要序列长度,比大小,交换元素。
那对上述的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)
}

可能的输出为:

[{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] = tmp
	return hi
}

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

总结:

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

欢迎补充指正!

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/83589945