Goland 中排序

刚接触go的时候,要排个序得重写Len()Swap()Less() 三个方法,好蛋疼的感觉。后现1.8版本后更新了sort库,排序用起来就简单多了。

1. 基本数据排序

基本数据为int、float64、string。int和float64直接比大小,string则是安顺序比较字符的ASCII码的大小

1.1 升序

直接使用sort.Ints()sort.Float64s()sort.Strings()方法就可以了,默认的排序就是升序的

package main

import (
    "fmt"
    "sort"
)

func main() {
    ints := [] int {5,6,9,8,7,1,2,5,4,6,3}
    float64s := [] float64 {3.1,4.1,5.9,2.6,5.3,5.8,9.7,9}
    strings := [] string {"g","u","o","k","e","guo","ke"}

    sort.Ints(ints)
    sort.Float64s(float64s)
    sort.Strings(strings)

    fmt.Printf("%v\n%v\n%v\n", ints, float64s, strings)
}

运行结果

[1 2 3 4 5 5 6 6 7 8 9]
[2.6 3.1 4.1 5.3 5.8 5.9 9 9.7]
[e g guo k ke o u]

1.2 降序

使用 sort.Reverse(slice) 来调换就可以了

package main

import (
    "fmt"
    "sort"
)

func main() {
    ints := [] int {5,6,9,8,7,1,2,5,4,6,3}
    float64s := [] float64 {3.1,4.1,5.9,2.6,5.3,5.8,9.7,9}
    strings := [] string {"g","u","o","k","e","guo","ke"}

    sort.Sort(sort.Reverse(sort.IntSlice(ints)))
    sort.Sort(sort.Reverse(sort.Float64Slice(float64s)))
    sort.Sort(sort.Reverse(sort.StringSlice(strings)))

    fmt.Printf("%v\n%v\n%v\n", ints, float64s, strings)
}

运行结果

[9 8 7 6 6 5 5 4 3 2 1]
[9.7 9 5.9 5.8 5.3 4.1 3.1 2.6]
[u o ke k guo g e]

2. 结构体排序

结构体直接使用sort.Slice(slice interface{}, less func(i, j int) bool)来排序。调整后面less函数的比较就可以得到升序或降序了

package main

import (
    "fmt"
    "sort"
)

func main() {
    people := []struct {
        Name string
        Age  int
    }{
        {"Gopher", 7},
        {"Alice", 55},
        {"Vera", 24},
        {"Bob", 75},
    }

    // Name升序
    sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
    fmt.Println("By name:", people)

    // 年龄降序
    sort.Slice(people, func(i, j int) bool { return people[i].Age > people[j].Age })
    fmt.Println("By age:", people)
}

运行结果

By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
By age: [{Bob 75} {Alice 55} {Vera 24} {Gopher 7}]
0%