下面由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)}

可能的输出为:

[{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)

总结: