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])
    })
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM