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  


// 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
}

相关推荐

  1. golang普通函数与闭函数使用示例

    2024-05-11 20:56:03       30 阅读
  2. golang系统函数整理

    2024-05-11 20:56:03       32 阅读
  3. Oracle常见程序使用Package

    2024-05-11 20:56:03       45 阅读
  4. 21-Golang数组 切片排序算法以及sort

    2024-05-11 20:56:03       67 阅读
  5. 如何使用Python函数和模块?

    2024-05-11 20:56:03       39 阅读
  6. PostgreSQL 函数

    2024-05-11 20:56:03       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-11 20:56:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-11 20:56:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-11 20:56:03       82 阅读
  4. Python语言-面向对象

    2024-05-11 20:56:03       91 阅读

热门阅读

  1. 解决FS4054低耐压批量时不良容易烧,FS4054H高耐压

    2024-05-11 20:56:03       32 阅读
  2. Linux专题-Makefile(2)

    2024-05-11 20:56:03       35 阅读
  3. SpringSecurity安全管理框架-(一)初识SpringSecurity

    2024-05-11 20:56:03       27 阅读
  4. 力扣:763. 划分字母区间

    2024-05-11 20:56:03       63 阅读