使用 sort.Interface接口 实现排序

2022-04-17  本文已影响0人  wayyyy

go 内部的sort 可以快速对于内置类型的数据进行排序。

package main

func main() {
    intValue := []int{10, 5, 20, 8}
    sort.Ints(intValue)
    fmt.Println(intValue)
}

其他类似方法还有Float64sStrings,可以对 []float64[]string 排序。

但假设,需要我们使用自定义的结构体来实现排序,那么该怎么做呢?sort包定义了 sort.Interface

type Interface interface {
    Len() int             // 获取元素数量
    Less(i, j int) bool   // i,j是序列元素的指数。
    Swap(i, j int)        // 交换元素
}

自定义的结构体,只要实现了上述3种方法,就可以调用 sort.Sort() 方法来实现排序。

type Student struct {
    Name         string
    MathScore    float64
    EnglishScore float64
}

type Students []*Student

func (s Students) Len() int {
    return len(s)
}

func (s Students) Less(i, j int) bool {
    // 优先按照数学成绩排序
    if s[i].MathScore != s[j].MathScore {
        return s[i].MathScore < s[j].MathScore
    }
    // 其次按照英语成绩排序
    return s[i].EnglishScore < s[j].EnglishScore
}

func (s Students) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

func main() {
    stus := Students{
        &Student{"zhang1", 100, 90},
        &Student{"zhang2", 100, 95},
        &Student{"li", 80, 96},
        &Student{"li", 80, 100},
    }

    sort.Sort(stus)     // 正序
    for _, stu := range stus {
        fmt.Println(stu)
    }

    sort.Sort(sort.Reverse(stus))   // 逆序
    for _, stu := range stus {
        fmt.Println(stu)
    }
}
上一篇下一篇

猜你喜欢

热点阅读