排序应该是我们日常工作中经常使用到的算法,一般通过系统自带的 sort 库即可实现简单排序,但如果有一些定制化的需求,那么应该怎么排序呢?本文将简单阐述Go中如何自定义排序规则。
从具体需求中看Go中如何自定义排序规则。
假设我们有一堆信封[w, h],w表示信封宽度,h表示信封高度。
现在我们需要对一堆信封排序,排序规则是按宽度从小到大,如果宽度相同,则按高度从大到小排。
Go中 sort 包内定义了排序接口,接口中定义了三个方法
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with index i
// must 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)
我们自定义排序主要就是要实现这三个接口,
Len()方法表示集合中元素个数,
Less()方法是比较两个元素的方法,也是自定义排序规则的核心方法,
Swap()方法是交换两个元素的方法。
让我们针对上面的需求做代码实现吧
type Envelop [][]int
func (e Envelop) Len() int {
return len(e)
}
// Less 实现 sort.Interface 接口的比较元素方法
func (e Envelop) Less(i, j int) bool {
// 排序规则如下:
// 1. 信封w按从小到大的顺序排序
// 2. 当信封w相同时,按信封h从小到大的顺序排序
return e[i][0] < e[j][0] || (e[i][0] == e[j][0] && e[i][1] < e[j][1])
}
// Swap 实现 sort.Interface 接口的交换元素方法
func (e Envelop) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}