Golang标准库——sort

sort 包提供了排序切片和用户自定义数据集的函数。
要使用 sort 排序,对象必须实现如下接口(切片已原生实现此接口):

type Interface interface {
    // Len方法返回集合中的元素个数
    Len() int
    // Less方法报告索引i的元素是否比索引j的元素小
    Less(i, j int) bool
    // Swap方法交换索引i和j的两个元素
    Swap(i, j int)
}
package main

import (
    "fmt"
    "sort"
)

// 自定义数据集
type byLength []string

// 实现接口
func (s byLength) Len() int {
	return len(s)
}

func (s byLength) Less(i, j int) bool {
	return len(s[i]) < len(s[j])
}

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

func main() {
    /* 内置切片 */
    var IntSlice []int = []int{ 1, 3, 6, 9, 4, 0, 5, 2, 8, 7 }
    var Float64Slice []float64 = []float64{ 1.0, 3.3, 5.6, 6.7, 2.9 }
    var StringSlice []string = []string{ "today", "is", "a", "good", "day" }

	// 判断是否为递增排序
	sort.IntsAreSorted(IntSlice)    // false 
	// 整型递增排序
    sort.Ints(IntSlice)    // [0 1 2 3 4 5 6 7 8 9]
	sort.IntsAreSorted(IntSlice)    // true
	// 在递增顺序的切片a中搜索x,返回x的索引。如果查找不到,返回值是x应该插入a的位置(以保证a的递增顺序)
	sort.SearchInts(IntSlice,  5)    // 5
	sort.SearchInts(IntSlice,  13)   // 10
	
	sort.Float64sAreSorted(IntSlice)    // false
	sort.Floats(Float64Slice)    // [1.0 2.9 3.3 5.6 6.7]
	sort.Float64sAreSorted(IntSlice)    // true
	sort.SearchFloat64s(Float64Slice, 5.6)    // 3
	sort.SearchFloat64s(Float64Slice, 4.8)    // 3
	
	sort.StringsAreSorted(IntSlice)    // false
	sort.Strings(StringSlice)    // [a day good is today]	
	sort.StringsAreSorted(IntSlice)    // true
	sort.SearchStrings(StringSlice, "is")    // 3
	sort.SearchStrings(StringSlice, "ok")    // 4


	/* 用户自定义数据集 */
	// 在主函数外定义数据类型,并实现接口。下面函数可接受的参数均为已实现此接口的数据类型
	var fruits byLength = byLength{"peach", "banana", "watermellon""apple"}
	// 判断是否已经按照接口的具体定义方式排好序
	sort.IsSorted(fruits)    // false
	// 按照接口的具体定义方式排序(非稳定排序)
	sort.Sort(fruits)    // [peach apple banana watermellon]
	// 按照接口的具体定义方式排序(稳定排序)
	sort.Stable(fruits)    // [peach apple banana watermellon]
	sort.IsSorted(fruits)    // true
	// 包装一个Interface接口并返回一个新的Interface接口,对返回的接口排序可生成递减序列。
	a := sort.Reverse(fruits)    // 返回一个接口Interface
	sort.Sort(a)    // &{[watermellon banana orange peach apple]}
}

附 sort 包连接:https://studygolang.com/pkgdoc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值