Go语言学习笔记—golang标准库sort包

文章目录

  • 前言
  • 一 排序接口
  • 二 相关函数汇总
  • 三 数据集合排序
    • 3.1 Sort排序方法
    • 3.2 IsSorted是否已排序方法
    • 3.3 Reverse逆序排序方法
    • 3.4 Search查询位置方法
  • 四 sort包支持的内部数据类型
    • 4.1 `[]int`排序
    • 4.2 `[]float64`排序
    • 4.3 `[]string`排序
    • 4.4 复杂结构: `[][]int`排序
    • 4.5 复杂结构体:`[]map[string]int [{"k":0}, {"k1":1}, {"k2":2}]`排序
    • 4.6 复杂结构体:`[]struct`排序


前言

sort包提供了排序切片和用户自定义数据集以及相关功能的函数。

sort包主要针对[]int[]float64[]string、以及其他自定义切片的排序。

主要包括:

  • 对基本数据类型切片的排序支持。
  • 基本数据元素查找。
  • 判断基本数据类型切片是否已经排好序。
  • 对排好序的数据集合逆序

一 排序接口

type Interface interface {
   
    Len() int	// 获取数据集合元素个数
    
    Less(i, j int) bool	// 如果i索引的数据小于j索引的数据,返回true,不会调用下面的Swap(),即数据升序排序。
    
    Swap(i, j int)	// 交换i和j索引的两个元素的位置
}

实例演示:

package main

import (
	"fmt"
	"sort"
)

type NewInts []uint

func (n NewInts) Len() int {
   
	return len(n)
}

func (n NewInts) Less(i, j int) bool {
   
	fmt.Println(i, j, n[i] < n[j], n)
	return n[i] < n[j]
}

func (n NewInts) Swap(i, j int) {
   
	n[i], n[j] = n[j], n[i]
}

func main() {
   
	n := []uint{
   1, 3, 2}
	sort.Sort(NewInts(n))
	fmt.Println(n)
}

运行结果:

[Running] go run "c:\Users\Mechrevo\Desktop\go_pro\test.go"
1 0 false [1 3 2]
2 1 true [1 3 2]
1 0 false [1 2 3]
[1 2 3]

[Done] exited with code=0 in 1.105 seconds

二 相关函数汇总

func Ints(a []int)
func IntsAreSorted(a []int) bool
func SearchInts(a []int, x int) int
func Float64s(a []float64)
func Float64sAreSorted(a []float64) bool
func SearchFloat64s(a []float64, x float64) int
func SearchFloat64s(a []float64, x float64) bool
func Strings(a []string)
func StringsAreSorted(a []string) bool
func SearchStrings(a []string, x string) int
func Sort(data Interface)
func Stable(data Interface)
func Reverse(data Interface) Interface
func IsSorted(data Interface) bool
func Search(n int, f func(int) bool) int

三 数据集合排序

3.1 Sort排序方法

对数据集合(包括自定义数据类型的集合)排序,需要实现sort.Interface接口的三个方法,即:

type Interface interface {
   
    Len() int	// 获取数据集合元素个数
    
    Less(i, j int) bool	// 如果i索引的数据小于j索引的数据,返回true,不会调用下面的Swap(),即数据升序排序。
    
    Swap(i, j int)	// 交换i和j索引的两个元素的位置
}

实现了这三个方法后,即可调用该包的Sort()方法进行排序。 Sort()方法定义如下:

func Sort(data Interface)

Sort()方法惟一的参数就是待排序的数据集合。

3.2 IsSorted是否已排序方法

sort包提供了IsSorted方法,可以判断数据集合是否已经排好顺序。IsSorted方法的内部实现依赖于我们自己实现的Len()和Less()方法:

func IsSorted(data Interface) bool {
   
    n := data.Len()
    for i := n - 1; i > 0; i

你可能感兴趣的:(Go语言进阶学习笔记,学习,golang)