This is the first article in the nuggets, has been in a book before the article, come in the feeling of the book is getting worse, want to move the article to the nuggets.

introduce

Golang, like Java and other languages, comes with a built-in sorting method that can be implemented quickly. Without further ado, first chestnut, then explain.

package main

import (
	"fmt"
	"math/rand"
	"sort"
	"strconv"
)

func main(a) {
	oneArr := make([]*One, 10)
	for i := 0; i < 10; i++ {
		oneArr[i] = &One{
			Name: "name" + strconv.FormatInt(int64(i), 10),
			Num:  rand.Intn(1000),}}for _, v := range oneArr {
		fmt.Print(v, "")
	}
	fmt.Println()
	sort.Sort(OneList(oneArr))
	for _, v := range oneArr {
		fmt.Print(v, "")
	}
	fmt.Println()

}

type One struct {
	Num  int
	Name string
}

type OneList []*One

func (this OneList) Len(a) int {
	return len(this)
}
func (this OneList) Less(i, j int) bool {
	return this[i].Num < this[j].Num
}
func (this OneList) Swap(i, j int) {
	this[i], this[j] = this[j], this[i]
}
Copy the code

The results

Implement sorting from smallest to largest

explain

Defines an OneList slice of type []*One using type type. OneLiit implements the Interface that’s defined in sort, the prototype

// A type, typically a collection, that satisfies sort.Interface can be // sorted by the routines in this package. The methods require that the // elements  of the collection be enumerated by an integer index. type Interface interface { // 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) }Copy the code
  • Len()The function returns the length of the sequence to be sorted

  • Less()The function returns a rule for the comparison required for sorting, and if the rule is met, the swap is performed

  • Swap()Exchange rules for sorting functions

So let’s rewrite these three functions for OneList

Create a new slice oneArr, randomly populate the data, and then call sort () in the sort package to sort. The Sort() function needs to pass an argument of type Interface. Use a cast to cast oneArr to Interface.

There is also a function in the sort package for Reverse sorting, sort.sort.reverse () for Reverse sorting

chestnutssort.Sort(sort.Reverse(OneList(oneArr)))I can sort in reverse

Results:Implement sorting from top to bottom

expand

Golang’s sort package defines some common sorting types for us

  • type IntSlice []int Sort of int slices
  • type Float64Slice []float64Sort of float64 slices
  • type StringSlice []stringSort of string slices

Look at an application chestnut:

package main

import (
	"fmt"
	"math/rand"
	"sort"
)

func main() {
	one := make([]int, 10)
	for i := 0; i < 10; i++ {
		one[i] = int(rand.Int31n(1000))
	}
	fmt.Println(one)
	sort.Sort(sort.IntSlice(one))
	fmt.Println(one)

}
Copy the code

Running results:

Okay, so that’s it.