使用 sort 来排序
sort 操作的对象通常是一个 slice, 需要满足三个基本的接口, 并且能够使用整数来索引
// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type 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)
}
对 []int 从小到大排序
package main
import (
"fmt"
"sort"
)
type IntSlice []int
func (s IntSlice) Len() int { return len(s) }
func (s IntSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] }
func main() {
a := []int{4, 3, 2, 1, 5, 9, 8, 7, 6}
sort.Sort(IntSlice(a))
fmt.Println("After sorted: ", a)
}
使用 sort.Ints 和 sort.Strings
golang 对常见的 []int 和 []string 分别定义了 IntSlice 和 StringSlice, 实现了各自的排序接口。而 sort.Ints 和 sort.Strings 可以直接对 []int 和 []string 进行排序, 使用起来非常方便
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{3, 5, 4, -1, 9, 11, -14}
//第一种方法 sort.Ints() 简单方式
sort.Ints(a)
fmt.Println(a) //[-14 -1 3 4 5 9 11]
//第二种方法 sort.IntSlice()和sort.Sort()结合使用
sort.Sort(sort.IntSlice(a))
fmt.Println(a) //[-14 -1 3 4 5 9 11]
ss := []string{"surface", "ipad", "mac pro", "mac air", "think pad", "idea pad"}
//第一种方法: sort.Strings()方法
sort.Strings(ss)
fmt.Println(ss)
//第二种方法: sort.StringSlice()和sort.Sort()结合使用
sort.Sort(sort.StringSlice(ss)) //正向排序
fmt.Printf("After : %v\n", ss)
sort.Sort(sort.Reverse(sort.StringSlice(ss))) //反向排序
fmt.Printf("After reverse: %v\n", ss)
}
使用 sort.Reverse 进行逆序排序
如果我们想对一个 sortable object 进行逆序排序,可以自定义一个type。但 sort.Reverse 帮你省掉了这些代码
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{4, 3, 2, 1, 5, 9, 8, 7, 6}
sort.Sort(sort.IntSlice(a)) //正序排序
fmt.Println("After: ", a) //After: [1 2 3 4 5 6 7 8 9]
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("After reversed: ", a) //After reversed: [9 8 7 6 5 4 3 2 1]
}
使用 sort.Stable 进行稳定排序
sort.Sort 并不保证排序的稳定性。如果有需要, 可以使用 sort.Stable
package main
import (
"fmt"
"sort"
)
type person struct {
Name string
Age int
}
type personSlice []person
func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }
func main() {
a := personSlice{
{
Name: "AAA",
Age: 55,
},
{
Name: "BBB",
Age: 22,
},
{
Name: "CCC",
Age: 0,
},
{
Name: "DDD",
Age: 22,
},
{
Name: "EEE",
Age: 11,
},
}
sort.Stable(a)
fmt.Println(a)
}
随机排序
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] })
fmt.Println(a) //[5 8 6 4 3 7 2 1]
}
警告:如果不调用 rand.Seed, 则每次运行程序时, 您都会获得相同的伪随机数序列。
本文暂时没有评论,来添加一个吧(●'◡'●)