• 使用sort包对任意类型元素的集合进行排序


    使用sort包的函数进行排序时,集合需要实现sort.Inteface接口,该接口中有三个方法:

    // Len is the number of elements in the collection.

    Len() int

    // Less reports whether the element with index i should sort before the element with index j.

    Less(i, j int) bool

    // Swap swaps the elements with indexes i and j.

    Swap(i, j int)

    例子(struct):

    //对任意对象进行排序

    type Person struct {

         name string

         age int

    }

    //为*Person添加String()方法,便于输出

    func (p *Person) String() string {

         return fmt.Sprintf("( %s,%d )", p.name, p.age)

    }

    type PersonList []*Person

    //排序规则:首先按年龄排序(由小到大),年龄相同时按姓名进行排序(按字符串的自然顺序)

    func (list PersonList) Len() int { return len(list) }

    func (list PersonList) Less(i, j int) bool {

        if list[i].age < list[j].age {

            return true

        } else if list[i].age > list[j].age {

            return false

        } else {

            return list[i].name < list[j].name

        }

    }

    func (list PersonList) Swap(i, j int) {

         var temp *Person = list[i]

         list[i] = list[j]

         list[j] = temp

    }

    func interfaceTest0203() {

         fmt.Println("------")

         p1 := &Person{"Tom", 19}

         p2 := &Person{"Hanks", 19}

         p3 := &Person{"Amy", 19}

         p4 := &Person{"Tom", 20}

         p5 := &Person{"Jogn", 21}

         p6 := &Person{"Mike", 23}

         pList := PersonList([]*Person{p1, p2, p3, p4, p5, p6})

         sort.Sort(pList)

         fmt.Println(pList)

        /*output: [( Amy,19 ) ( Hanks,19 ) ( Tom,19 ) ( Tom,20 ) ( Jogn,21 ) ( Mike,23 )] */

    }

    slice 排序:

    方式一:默认从小到大

    //func Ints(x []int) { Sort(IntSlice(x)) }

    sort.Ints() 

    方式二:自定义从大到小还是从小到大

    sort.Slice(a, func(i, j int) bool {

       return a[i] < a[j]

    })

     

  • 相关阅读:
    LeetCode OJ Remove Duplicates from Sorted Array II
    LeetCode OJ 75. Sort Colors
    LeetCode OJ 74. Search a 2D Matrix
    LeetCode OJ 73. Set Matrix Zeroes
    Taglist
    NERDTree
    Beyond Compare 4
    Beyond compare vs kdiff3
    切換 java compiler 版本
    PE+ 1.0 ( Pump Express Plus 1.0 )
  • 原文地址:https://www.cnblogs.com/china-golang/p/15921935.html
Copyright © 2020-2023  润新知