sort.Slice无法保证稳定性
sort.SliceStable可以保证稳定性
函数中不要带=号
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{2, 2, 2, 3}
type pair struct {
i int
v int
}
pairs := make([]pair, 0)
for i, num := range nums {
pairs = append(pairs, pair{i, num})
}
fmt.Println(pairs)// [{0 2} {1 2} {2 2} {3 3}]
sort.SliceStable(pairs, func(i, j int) bool {
if pairs[i].v < pairs[j].v {
return true
}
return false
})
fmt.Println(pairs)// [{0 2} {1 2} {2 2} {3 3}]
}