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


前言

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-- {
   
        if data.Less(i, i-1) {
   
            return false
        }
    }
    return true
}

3.3 Reverse逆序排序方法

sort包提供了Reverse()方法,将数据按Less()定义的排序方式逆序排序,而不必修改Less()代码。方法定义如下:

func 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值