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
}
相关推荐
ktkiko111 分钟前
顶层架构 - 消息集群推送方案
java·开发语言·架构
楠奕1 分钟前
python中使用neo4j
开发语言·python·neo4j
南斯拉夫的铁托13 分钟前
labelimg安装及使用指南(yolo)
开发语言·python·yolo
六bring个六36 分钟前
文件系统交互实现
开发语言·c++·qt·交互
jingyu飞鸟42 分钟前
Centos7系统(最小化安装)安装zabbix7版本详细文章、nginx源代码配置、php源代码、mysql-yum安装
开发语言·php
dhxhsgrx1 小时前
PYTHON训练营DAY27
开发语言·python
小山菌1 小时前
mac中加载C++动态库文件
开发语言·c++·macos
獨枭1 小时前
使用 163 邮箱实现 Spring Boot 邮箱验证码登录
java·spring boot·后端
维基框架1 小时前
Spring Boot 封装 MinIO 工具
java·spring boot·后端
秋野酱1 小时前
基于javaweb的SpringBoot酒店管理系统设计与实现(源码+文档+部署讲解)
java·spring boot·后端