[go] 快速排序

实现gosort.Interface接口,实现自定义数据类型的快速排序

package main

import (
	"log"
	"sort"
)

type myStructExp struct {
     
	id int
}
type myStructExps []*myStructExp

func (s myStructExps) Len() int {
     
	return len(s)
}

func (s myStructExps) Less(i, j int) bool {
     
	return s[i].id < s[j].id
}

func (s myStructExps) Swap(i, j int) {
     
	s[i], s[j] = s[j], s[i]
}

func main() {
     
	var ss myStructExps
	for i := 10; i > 0; i-- {
     
		d := &myStructExp{
     id: i}
		ss = append(ss, d)
	}
	for _, s := range ss {
     
		log.Println(s.id)
	}
	log.Println("==========")
	sort.Sort(ss)
	for _, s := range ss {
     
		log.Println(s.id)
	}

}

程序输出

2020/08/29 16:23:01 10
2020/08/29 16:23:01 9
2020/08/29 16:23:01 8
2020/08/29 16:23:01 7
2020/08/29 16:23:01 6
2020/08/29 16:23:01 5
2020/08/29 16:23:01 4
2020/08/29 16:23:01 3
2020/08/29 16:23:01 2
2020/08/29 16:23:01 1
2020/08/29 16:23:01 ==========
2020/08/29 16:23:01 1
2020/08/29 16:23:01 2
2020/08/29 16:23:01 3
2020/08/29 16:23:01 4
2020/08/29 16:23:01 5
2020/08/29 16:23:01 6
2020/08/29 16:23:01 7
2020/08/29 16:23:01 8
2020/08/29 16:23:01 9
2020/08/29 16:23:01 10

注意事项,必须实现定义 type myStructExps []*myStructExp 类型,然后在这个类型上实现 sort.Interface 接口

你可能感兴趣的:(go,Linux)