Go 排序方式
參考:
https://segmentfault.com/a/1190000016514382 (值得一看)
Go 常見排序方式
整數、浮點數、字符串切片排序
sort包提供了一下幾種排序函數:
- sort.Ints(x []int)
- sort.Float64s(x []float64)
- sort.Strings(x []string)
使用自定義比較器進行排序
- 使用sort.Slice(x interfacec{}, less func(i, j int) bool)進行排序(快速排序 + 堆排序 + 希爾排序),其中less()為自定義的排序邏輯(使用匿名函數定義排序規則);
- sort.SliceStable(x interfacec{}, less func(i, j int) bool)使用方法與sort.Slice(...)一致,唯一的不同點是sort.SliceStable(...)是一種穩定的排序方式(插入排序 + 歸并排序);
結構體排序
對于結構體切片,可以直接使用sort.Slice()或者sort.SliceStable()針對某個字段進行排序。其次,還可以令任意類型(主要針對結構體)實現sort.Interface接口來進行排序。sort.Interface中的三個方法:
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}]總結
- 上一篇: Excel之Char.Chr.Chrw函
- 下一篇: 三伏贴真的有效果吗