首页 > 编程语言 > 详细

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

时间:2019-12-31 12:44:41      阅读:204      评论:0      收藏:0      [点我收藏+]

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切片的快速排序

原文:https://www.cnblogs.com/roastpiglet/p/12123524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!