golang排序实践
Contents
[NOTE] Updated August 29, 2019. This article may have outdated content or subject matter.
对int, float64, string列表进行排序
可以直接使用库函数, 进行升序排序, 目前有以下三个库函数sort.Ints
,sort.Strings
,sort.Float64s
|
|
使用自定义比较器
从go1.8后,可以直接使用sort.Slice
, 使用自定义的比较函数less(i, j int) bool
. 如果想稳定排序,可以使用sort.SliceStable
sort.Slice内部使用的接口和反射来实现的,效率上面会打一定的折扣。
|
|
实现排序接口
- 使用
sort.Sort
和sort.Stable
函数 只要实现了
sort.Interface
接口的集合,都可以通过上面的两个函数进行排序。1 2 3 4 5 6 7 8 9
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) }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
package main import ( "fmt" "sort" ) type User struct { Name string Age int } type ByAge []User func (a ByAge) Len() int { return len(a) } func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age } func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func main() { users := []User{ User{"test", 12}, User{"james", 32}, User{"bob", 18}, User{"alice", 16}, } sort.Sort(ByAge(users)) fmt.Println(users) }
性能对比
Slice vs Sorting Type (of Slice) with Sort implementation
|
|
测试结果:
|
|
参考
Author beyondkmp
LastMod 2019-08-29