zoukankan      html  css  js  c++  java
  • golang 自定义类型的排序sort

    sort包中提供了很多排序算法,对自定义类型进行排序时,只需要实现sort的Interface即可,包括:

    func Len() int {... }
    func Swap(i, j int) {... }
    func Less(i, j int) bool {... }

    使用方法举例如下:

    package main
    
    
    import (
        "fmt"
        "sort"
    )
    
    type Person struct {
        Name string
        Age  int
    }
    
    func (p Person) String() string {
        return fmt.Sprintf("%s: %d", p.Name, p.Age)
    }
    
    // ByAge implements sort.Interface for []Person based on
    // the Age field.
    type ByAge []Person
    
    func (a ByAge) Len() int           { return len(a) }
    func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
    
    func main() {
        people := []Person{
            {"Bob", 31},
            {"John", 42},
            {"Michael", 17},
            {"Jenny", 26},
        }
    
        fmt.Println(people)
        sort.Sort(ByAge(people))
        fmt.Println(people)
    }
    

    Output:

    [Bob: 31 John: 42 Michael: 17 Jenny: 26]
    [Michael: 17 Jenny: 26 Bob: 31 John: 42]

    参考

  • 相关阅读:
    三数之和
    167
    二分搜索树
    687
    索引堆
    二分查找 leetcode704
    leetcode 56合并区间 java
    leetcode 1046
    堆的数据结构java
    leetcode 493
  • 原文地址:https://www.cnblogs.com/lanyangsh/p/8325846.html
Copyright © 2011-2022 走看看