Go 排序方式
參考:
https://segmentfault.com/a/1190000016514382 (值得一看)
Go 常見排序方式
整數(shù)、浮點(diǎn)數(shù)、字符串切片排序
sort包提供了一下幾種排序函數(shù):
- sort.Ints(x []int)
- sort.Float64s(x []float64)
- sort.Strings(x []string)
使用自定義比較器進(jìn)行排序
- 使用sort.Slice(x interfacec{}, less func(i, j int) bool)進(jìn)行排序(快速排序 + 堆排序 + 希爾排序),其中l(wèi)ess()為自定義的排序邏輯(使用匿名函數(shù)定義排序規(guī)則);
- sort.SliceStable(x interfacec{}, less func(i, j int) bool)使用方法與sort.Slice(...)一致,唯一的不同點(diǎn)是sort.SliceStable(...)是一種穩(wěn)定的排序方式(插入排序 + 歸并排序);
結(jié)構(gòu)體排序
對(duì)于結(jié)構(gòu)體切片,可以直接使用sort.Slice()或者sort.SliceStable()針對(duì)某個(gè)字段進(jìn)行排序。其次,還可以令任意類型(主要針對(duì)結(jié)構(gòu)體)實(shí)現(xiàn)sort.Interface接口來進(jìn)行排序。sort.Interface中的三個(gè)方法:
type Interface interface {Len() intLess(i, j int) boolSwap(i, j int) }例如:
type Person struct {name stringage int }type People []Personfunc (p People) Len() int {return len(p) }func (p People) Less(i, j int) bool {return p[i].name > p[j].name/*按名字降序排序,如果名字相同,按年齡升序排序。if p[i].name == p[j].name {return p[i].age > p[j].age}return p[i].name > p[j].name*/}func (p People) Swap(i, j int) {p[i], p[j] = p[j], p[i] }func main() {family := []Person{{name: "mother", age: 39},{name: "father", age: 40},{name: "son", age: 20},}fmt.Printf("before sort : %v\n", family)// 是否排序fmt.Println(sort.IsSorted(People(family)))sort.Sort(People(family))fmt.Println(sort.IsSorted(People(family)))fmt.Printf("after sort : %v\n", family) } // before sort : [{mother 39} {father 40} {son 20}] // false // true // after sort : [{son 20} {mother 39} {father 40}]總結(jié)
- 上一篇: Excel之Char.Chr.Chrw函
- 下一篇: 云原生初探