Golang對整數slice依大小排序的方式如下。
範例環境:
- Go 1.19
使用sort.Ints將整數slice由小到大排序。
將整數slice轉為sort.IntSlice,然後用sort.Reverse轉為sort.Interface傳入sort.Sort將整數slice由大到小排序,。
main.go
package main
import (
"fmt"
"sort"
)
func main() {
ints := []int{5, 3, 1, 2, 4}
sort.Ints(ints)
fmt.Println(ints) // [1 2 3 4 5]
sort.Sort(sort.Reverse(sort.IntSlice(ints)))
fmt.Println(ints) // [5 4 3 2 1]
}
沒有留言:
張貼留言