golang内置包里面的sort.Slice 切片排序函数使用示例

go语言里面用的最多的数据类型应该是切片Slice了, 今天就给大家介绍这个go内置包里面的切片排序函数的使用方法

函数原型 func Slice(x any, less func(i, j int) bool)

参数说明 这个函数有2个参数, 第一个是你要进行排序的slice切片,地个要传递一个函数,这个函数就是你要对你的数据进行怎么样的排序。

示例代码:

var s1 = []int{133,144,21,69,83,37,56,38,68,123,23,89,170,8,76,120} // 这个就是要排序的int切片

sort.Slice(s1, func(i, j int) bool { return s1[i] > s1[j] })

// 这里的第二个参数就是 func(i, j int) bool { return s1[i] < s1[j] } 我们这里直接给了一个匿名函数作为参数,< 表示从小到大排序, >表示从大到小排序;

//这里的这个函数因为是切片类型 其就是引用数据类型,所以不需要接收数据

怎么样,是不是很简单, 其他2个函数用法可参考后面的源码使用。。。。

Slice排序函数源码参考, 路径 /src/sort/slice.go

Go 复制代码
// Slice sorts the slice x given the provided less function.
// It panics if x is not a slice.
//
// The sort is not guaranteed to be stable: equal elements
// may be reversed from their original order.
// For a stable sort, use SliceStable.
//
// The less function must satisfy the same requirements as
// the Interface type's Less method.
func Slice(x any, less func(i, j int) bool) {
	rv := reflectlite.ValueOf(x)
	swap := reflectlite.Swapper(x)
	length := rv.Len()
	limit := bits.Len(uint(length))
	pdqsort_func(lessSwap{less, swap}, 0, length, limit)
}

// SliceStable sorts the slice x using the provided less
// function, keeping equal elements in their original order.
// It panics if x is not a slice.
//
// The less function must satisfy the same requirements as
// the Interface type's Less method.
func SliceStable(x any, less func(i, j int) bool) {
	rv := reflectlite.ValueOf(x)
	swap := reflectlite.Swapper(x)
	stable_func(lessSwap{less, swap}, rv.Len())
}

// SliceIsSorted reports whether the slice x is sorted according to the provided less function.
// It panics if x is not a slice.
func SliceIsSorted(x any, less func(i, j int) bool) bool {
	rv := reflectlite.ValueOf(x)
	n := rv.Len()
	for i := n - 1; i > 0; i-- {
		if less(i, i-1) {
			return false
		}
	}
	return true
}
相关推荐
pengyu5 分钟前
【Java设计原则与模式之系统化精讲:零】 | 编程世界的道与术(理论篇)
java·后端·设计模式
Aurora_NeAr5 分钟前
深入浅出Docker
后端
DemonAvenger9 分钟前
减少内存分配:Go中值类型与指针类型的选择
性能优化·架构·go
程序员岳焱11 分钟前
16.Java Annotation注解:元数据与代码增强
java·后端·编程语言
瀚海澜生13 分钟前
redis系列(2)——AOF日志和RDB快照
后端
努力学习的小廉27 分钟前
我爱学算法之—— 前缀和(中)
开发语言·redis·算法
想带你从多云到转晴1 小时前
02. java: 类与对象
java·开发语言
abments1 小时前
基于ReAction范式的问答系统实现demo
开发语言·python
面朝大海,春不暖,花不开1 小时前
Spring Security默认配置覆盖指南
java·后端·spring
修电脑的猫1 小时前
带有输入的CDS和程序调用
开发语言·lua