Go语言golang调用sort.Slice实现struct切片的快速排序

Posted roastpiglet

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言golang调用sort.Slice实现struct切片的快速排序相关的知识,希望对你有一定的参考价值。

sort.Slice声明

func Slice(slice interface{}, less func(i, j int) bool) {
    rv := reflectValueOf(slice)
    swap := reflectSwapper(slice)
    length := rv.Len()
    quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length))
}

实际使用

和C++的sort模板类似,只需要实现less函数,Go特别的是传入的函数不是直接传入less,而是一个匿名函数,匿名函数的参数是两个下标,表示两个比较元素在切片中的下标

type Person struct {
    h int
    k int
}

func PersonLess(p Person, other Person) bool{
    if p.h > other.h {
        return true
    } else if p.h < other.h {
        return false
    } else {
        return p.k <= other.k
    }
}

func reconstructQueue(people [][]int) [][]int {
    personSlice := NewPersonSlice(people)
    sort.Slice(personSlice, func(i, j int) bool {
        return PersonLess(personSlice[i], personSlice[j])
    })
}

以上是关于Go语言golang调用sort.Slice实现struct切片的快速排序的主要内容,如果未能解决你的问题,请参考以下文章

贪心算法——区间问题

lua和go混合调用调试记录支持跨平台(通过C和LuaJit进行实现)

$each $position $sort $slice

[go]grpc远程接口调用实现

一学就会,手把手教你用Go语言调用智能合约

编程实践用 go 语言实现一个SQL DSL