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