go 使用 sort 对切片进行排序


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]


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM