type User struct {
Name string
Score int}type Users []User
golang中想要自定义排序,自己的结构要实现三个方法:
// 摘自: $GOROOT/src/sort/sort.gotype Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)}
func myqsort(us []User, lo, hi int) {
if lo < hi {
pivot := partition(us, lo, hi)
myqsort(us, lo, pivot-1)
myqsort(us, pivot+1, hi)
}}func partition(us []User, lo, hi int) int {
tmp := us[lo]
for lo < hi {
for lo < hi && us[hi].Score >= tmp.Score {
hi--
}
us[lo] = us[hi]
for lo < hi && us[lo].Score <= tmp.Score {
lo++
}
us[hi] = us[lo]
}
us[lo] = tmp return hi}