代码改变世界

go 使用 sort 对切片进行排序

2021-09-20 10:20  jetwill  阅读(806)  评论(0编辑  收藏  举报

golang对slice的排序

golang里面需要使用sort包,并且实现几个接口Len, Swap, Less

sort 包排序demo

假如现在有个slice 叫做 ids 里面保存的数据类型是int32

package main

import (
	"fmt"
	"sort"
)

type Int32List []int32

func (s Int32List) Len() int           { return len(s) }
func (s Int32List) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s Int32List) Less(i, j int) bool { return s[i] < s[j] }

func main() {
	var ids []int32
	ids = append(ids, 20, 50, 5, 100, 88)

	// 对ids 进行排序,这样排序是in place 形式的.
	sort.Sort(Int32List(ids))
	fmt.Println(ids)
}
//out: [5 20 50 88 100]