Go 排序 sort.Slice 及其他方法

自定义排序[最常用]

sort.Slice 不稳定排序
sort.SliceStable 稳定排序

family := []struct {
    Name string
    Age  int
}{
    {"Alice", 23},
    {"David", 2},
    {"Eve", 2},
    {"Bob", 25},
}

// Sort by age, keeping original order or equal elements.
sort.SliceStable(family, func(i, j int) bool {
    return family[i].Age < family[j].Age
})
fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

ints, float64s or strings 排序

sort.Ints
sort.Float64s
sort.Strings

s := []int{4, 2, 3, 1}
sort.Ints(s)
fmt.Println(s) // [1 2 3 4]

你可能感兴趣的:(Go,golang,排序算法)