sort标准库的介绍和使用

本文详细介绍了Go语言标准库sort包的功能,包括对基本数据类型切片的排序、自定义数据集排序方法、相关函数如IsSorted、Reverse和Search,以及如何处理复杂结构如二维切片和结构体的排序。

sort标准库

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

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

主要包括:

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

1. 排序接口

type Interface interface {
   
   
    Len() int	// 获取数据集合元素个数
    
    Less(i, j int) bool	// 如果i索引的数据小于j索引的数据,返回true,Swap(),即数据升序排序,false 不调用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)
}

2. 相关函数汇总

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. 数据集合排序

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值