How does Golang language sort data efficiently?

Hello, I'm frank. Welcome to click on the blue text below the title, "Golang language development stack" to pay attention to the official account. Set as star mark to receive push articles at the first time. Scan the code at the end of the text and add groups to learn Golang language together.

01

introduce

In the development of Golang language project, we often encounter the problem of data sorting. The sort package of Golang language standard library provides us with the function of data sorting. We can directly use the sort.Sort() function to sort the data. The bottom implementation of the sort.Sort() function is based on fast sorting, and different sorting algorithms are selected according to the specific situation of the target data. In this paper, we introduce the use of sort packet sorting data.

02

Slice sorting

In the sort package of Golang language standard library, the sort.Sort() function is used for data sorting. This function requires an input parameter of interface type sort.Interface, which contains three methods, Len(), Less() and Swap(). That is, if we need to use the sort function of the sort package to sort the data, the first input parameter data needs to implement these three methods, or it is understood that the slice of any element type implements these three methods, we can use the sort.Sort() function to sort the data.

sort package code:

type Interface interface {
 Len() int // Number of elements in the collection
 Less(i, j int) bool // Describes the order of elements
 Swap(i, j int) // Exchange elements with indexes i and j
}

func Sort(data Interface)

It should be noted that the sort.Sort() function cannot guarantee the stability of data sorting. If you need to ensure the stability of data sorting, you can use the sort.Stable() function. "Stable" means that the values of a and b in the original data are equal, a before sorting is in front of b, and a after sorting is still in front of b.

In order to facilitate readers' understanding, we use the slice of int type as an example to introduce the use of the sort.Sort() function. We define a type IntSlice []int, implement three methods defined for the sort.Interface interface type for the type IntSlice, and then use the sort.Sort() function to sort the data.

Example code:

package main

import (
 "fmt"
 "sort"
)

type IntSlice []int

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

func (s IntSlice) Less(i, j int) bool {
 return s[i] > s[j]
}

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

func main () {
 intSlice := IntSlice([]int{1, 3, 5, 7, 9})
 fmt.Println(intSlice) // Before sorting
 sort.Sort(intSlice)
 fmt.Println(intSlice) // After sorting
}

Output structure:

[9 7 5 3 1]
[1 3 5 7 9]

After reading this, I believe that smart readers have understood how to use sort.Sort(). At the same time, they will also have a question. Does it need to be so troublesome every time they use sort.Sort() to sort data? I might as well write a traversal sorting data myself.

Yes, of course, it doesn't need to be so troublesome. The sort package has helped us encapsulate common functions, and we can use them directly. Therefore, the above example code can sort the data using the sort.Ints() function.

Example code:

func main () {
 intSlice := IntSlice([]int{9, 7, 5, 3, 1})
 fmt.Println(intSlice) // Before sorting
 sort.Ints(intSlice)
 fmt.Println(intSlice) // Sort the data using sort.Ints()
}

In addition to sort.Ints(), there are also sort.Float64s(), sort.Strings().

03

Custom collection sorting

In the development of Golang language projects, we often use structs. What should we do if we need to sort the slices of struct types?

We can implement the three methods according to the way of Part 01, and then call the sort.Sort() function. Of course, the sort package also encapsulates the function sort.Slice() for sorting structure type slices. However, in addition to sorting data, we need to provide a parameter of the Less() function type.

Example code:

people := []struct {
  Name string
  Age  int
 }{
  {"Gopher", 7},
  {"Alice", 55},
  {"Vera", 24},
  {"Bob", 75},
 }
 sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
 fmt.Println("By name:", people)

 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
 fmt.Println("By age:", people)

Output results:

By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]

04

summary

In this article, we introduced how to use the Golang language standard library sort package to sort data. It should be noted that in addition to the types used in this article, any other type can call the sort.Sort() function to sort data as long as it implements the three methods of sort.Interface.

In addition, in addition to sorting data, the sort package also provides us with the search function sort.Search(). Interested readers can read the official standard library documents of Golang language for more information.

Posted by PhaZZed on Thu, 11 Nov 2021 22:23:17 -0800