Golang 如何对int切片进行排序

Golang 如何对int切片进行排序

Golang中提供了sort包来对切片进行排序,其中包括对int切片的排序。本文将介绍使用sort包对int切片进行排序的方法。

排序方法

sort包提供了sort.Ints()函数来对int切片进行排序,该函数有一个参数即为待排序的int切片:

package main

import (
    "fmt"
    "sort"
)

func main() {
    intSlice := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
    sort.Ints(intSlice)
    fmt.Println(intSlice)
}

以上代码将输出:[1 1 2 3 3 4 5 5 5 6 9]

sort包也提供了sort.Sort()函数对实现了sort.Interface接口的自定义类型进行排序,sort.Interface接口包括三个方法:

  • Len() int
  • Less(i, j int) bool
  • Swap(i, j int)

其中Len()方法返回切片的长度,Less()方法用于判断两个元素的大小,Swap()方法用于交换两个元素的位置。我们可以通过实现这三个方法来对自定义类型进行排序。例如,对于一个实现了sort.Interface接口的Person类型,可以使用sort.Sort()函数进行排序:

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Age  int
    Name string
}

type PersonList []Person

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

func (p PersonList) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}

func (p PersonList) Less(i, j int) bool {
    return p[i].Age < p[j].Age
}

func main() {
    personList := []Person{
        {Age: 18, Name: "Lucy"},
        {Age: 21, Name: "Tom"},
        {Age: 16, Name: "Lily"},
        {Age: 23, Name: "Jackie"},
        {Age: 19, Name: "Mike"},
    }
    sort.Sort(PersonList(personList))
    fmt.Println(personList)
}

以上代码将输出:[{16 Lily} {18 Lucy} {19 Mike} {21 Tom} {23 Jackie}]

结论

在Golang中,使用sort包可以对int切片进行排序,sort.Ints()函数提供了对int切片的快速排序方法,sort.Sort()函数提供了对实现了sort.Interface接口的自定义类型的排序方法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程