golang: sort库基本使用


go的sort库一般用于对slice排序
待排序slice的数据类型需要实现以下接口:

type Interface interface {
	Len() int	//Len
	Less(i, j int) bool	//比较
	Swap(i, j int)	//交换
}

对于实现以上接口的数据类型,可以用sort.Sort()排序:

package main

import (
	"fmt"
	"sort"
)

type Nodes []struct {
	x, y int
}

func (a Nodes) Len() int {
	return len(a)
}
func (a Nodes) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}
func (a Nodes) Less(i, j int) bool {
	if a[i].x != a[j].x {
		return a[i].x < a[j].x
	}
	return a[i].y < a[j].y
}
func main() {
	a := Nodes{
		{
			2, 3,
		},
		{
			2, 1,
		},
		{
			3, 2,
		},
		{
			1, 4,
		},
	}
	sort.Sort(a)
	fmt.Println(a)
}
/*
结果:
[{1 4} {2 1} {2 3} {3 2}]
*/

sort.Ints()和sort.Strings()和sort.Float64s可以直接对[]int和[]string,[]float64从小到达排序:
底层原理是会帮你将[]int转为sort.IntSlice类型,而IntSlice类型实现了上面的接口。

package main

import (
	"fmt"
	"sort"
)

func main() {
	//sort.Ints()
	//对[]int从小到大排序
	a := []int{3, 2, 1, 5, 4}
	sort.Ints(a)
	fmt.Println(a)

	//sort.Strings()
	//对[]string从小到达排序
	s := []string{"abs", "sda", "asdf", "qefasd"}
	sort.Strings(s)
	fmt.Println(s)
}
/*
结果:
[1 2 3 4 5]
[abs asdf qefasd sda]
*/

如果要逆序排序,可以修改接口的Less函数实现,但是这样比较麻烦。
sort.Reverse()可以将实现了接口的类型传入,返回一个Less()函数反转的新类型,从而实现逆序排序:

package main

import (
	"fmt"
	"sort"
)

type Nodes []struct {
	x, y int
}

func (a Nodes) Len() int {
	return len(a)
}
func (a Nodes) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}
func (a Nodes) Less(i, j int) bool {
	if a[i].x != a[j].x {
		return a[i].x < a[j].x
	}
	return a[i].y < a[j].y
}
func main() {
	a := Nodes{
		{
			2, 3,
		},
		{
			2, 1,
		},
		{
			3, 2,
		},
		{
			1, 4,
		},
	}
	sort.Sort(a)//排序
	fmt.Println(a)
	sort.Sort(sort.Reverse(a))//逆序排序
	fmt.Println(a)
}
/*
结果:
[{1 4} {2 1} {2 3} {3 2}]
[{3 2} {2 3} {2 1} {1 4}]
*/

sort.Reverse()实现原理比较简单,就是多套了一层结构,
在新的一层里帮你把Less的比较顺序反转了:

type reverse struct {
	Interface	//Interface是排序需要实现的那个接口,在此基础上套了一层reverse类型.
}
//sort.Reverse():
func Reverse(data Interface) Interface {
	return &reverse{data}
}
//主要是这一步,帮你修改了Less的顺序:
func (r reverse) Less(i, j int) bool {
	return r.Interface.Less(j, i)
}

sort库的其他函数这里不介绍了,有需要的时候可以去看源码。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值