The use of the sort library of go language (how to sort in go language)

The use of the sort library of go language (how to sort in go language)

First of all, if you don't have a compiler, you can type code through this URL: Lightly

Introduction

The sort package is a package in the Go language standard library, which provides functions to sort slices. Slices of any comparable type (such as integers, floats, and strings) can be sorted using the sort package.
The following are the two main sorting functions in the sort package:

  • sort.Sort(): Sorts a slice that implements the sort.Interface interface in-place.
  • sort.Stable(): Perform a stable sort on a slice that implements the sort.Interface interface (the order in which elements are equal in the sorted result will not change).

In order for a type to be sorted using the sort package, the type must implement the sort.Interface interface. This interface defines three methods:

  • Len(): Returns the length of the slice.
  • Swap(i, j int): Swaps the elements with indices i and j in the slice.
  • Less(i, j int) bool: Returns whether the element with index i should be sorted before the element with index j.

For example, if we have a string slice that needs to be sorted, we can implement the following interface:

type StringSlice []string

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

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

func (s StringSlice) Less(i, j int) bool {
    
    
    return s[i] < s[j]
}

In the above code, we defined a new type named StringSlice, which represents a slice of type String. We then implement the three methods defined in the sort.Interface interface for this type.

// 对字符串切片进行排序
strs := []string{
    
    "apple", "orange", "banana", "grape"}
sort.Sort(StringSlice(strs))
fmt.Println(strs)
// Output: [apple banana grape orange]

In the above code, we defined a new type named StringSlice, which represents a slice of type String. We then implement the three methods defined in the sort.Interface interface for this type.

// 对字符串切片进行排序
strs := []string{
    
    "apple", "orange", "banana", "grape"}
sort.Sort(StringSlice(strs))
fmt.Println(strs)
// Output: [apple banana grape orange]

In the above code, we created a slice of strings and sorted it alphabetically (from A to Z) using the sort.Sort() function. We call the function by converting the slice to a StringSlice type, and the final output shows that the slice has been successfully sorted.

It should be noted that we can pass any slice type that implements the sort.Interface interface in the sort function. Therefore, we can easily sort slices of different types, such as integers, floats, and custom types, etc.

example

Given a list of persons, each person consists of two fields name and age. Please write a program to sort the list of people according to age from youngest to oldest, and output the sorted results.

Sort the list of people by age

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    
    
    Name string
    Age  int
}

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{
    
    
        {
    
    "Alice", 25},
        {
    
    "Bob", 20},
        {
    
    "Charlie", 30},
        {
    
    "Dave", 18},
    }

    sort.Sort(ByAge(people))
    fmt.Println(people)
}

In the above code, we defined a Person type, which contains two fields, name and age. We also define a ByAge type, which is a Person slice type, and implement the three methods defined in the sort.Interface interface for this type. Among them, the Less() method is used to compare the age.

In the main() function, we create a people slice and initialize four people's information. We then sort the list of persons by age from youngest to oldest by converting the slice to the ByAge type and calling the sort.Sort() function. Finally, we print out the result.

operation result:

insert image description here

Sort a slice of strings alphabetically

Given a slice of strings, write a program that sorts them alphabetically (A to Z) and outputs the sorted result.

package main

import (
    "fmt"
    "sort"
)

func main() {
    
    
    strs := []string{
    
    "apple", "orange", "banana", "grape"}
    sort.Strings(strs)
    fmt.Println(strs)
}

In the above code, we created a string slice and initialized four elements. We then sort the slice alphabetically using the sort.Strings() function and print out the result.

operation result:
insert image description here

Sort slices by float size

Given a slice of floating point numbers, please write a program that sorts the floating point numbers from small to large, and outputs the sorted results.

package main

import (
    "fmt"
    "sort"
)

func main() {
    
    
    nums := []float64{
    
    3.14, 1.23, 4.56, 2.71}
    sort.Float64s(nums)
    fmt.Println(nums)
}

In the code above, we create a slice of floats and initialize four elements. Then, we use the sort.Float64s() function to sort the slice in ascending order of float size, and print out the result.

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130114680