go排序方法总结

1、方法总结

  • sort.Ints
  • sort.Floats
  • sort.Strings
  • sort.SliceStable
  • sort.Interface{}

2、实例

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


//sort.SliceStable()
family := []struct {
    Name string
    Age  int
}{
    {"Alice", 23},
    {"David", 2},
    {"Eve", 2},
    {"Bob", 25},
}
// 用 age 排序,年龄相等的元素保持原始顺序
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}]
 //下面实现排序order by age asc, name desc,如果 age 和 name 都相等则保持原始排序
sort.SliceStable(family, func(i, j int) bool {
    if family[i].Age != family[j].Age {
        return family[i].Age < family[j].Age
    }
    return strings.Compare(family[i].Name, family[j].Name) == 1
})
fmt.Println(family) // [{Eve 2} {David 2} {Alice 23} {Bob 25}]


//sort.Interface{}
type Person struct {
    Name string
    Age  int
}
// ByAge 通过对age排序实现了sort.Interface接口
type ByAge []Person
func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func main() {
    family := []Person{
        {"David", 2},
        {"Alice", 23},
        {"Eve", 2},
        {"Bob", 25},
    }
    sort.Sort(ByAge(family))
    fmt.Println(family) // [{David, 2} {Eve 2} {Alice 23} {Bob 25}]

    sort.
}

  

posted @ 2023-02-13 14:34  ☞@_@  阅读(34)  评论(0)    收藏  举报