Go语言数组排序
Go语言内置包sort针对[]int, []float64, []string 3种切片类型提供排序、查找操作的函数。
import (
"fmt"
"sort"
)
func main() {
s := []int{5, 2, 9, 6}
sort.Sort(sort.IntSlice(s))
fmt.Println(s)
}
// [2 5 6 9]
对于自定义的集合,只要实现了sort.Interface接口,就可以通过sort包内的函数进行排序、查找操作。$GOROOT\src\sort\slice.go中sort.Interface定义了三个方法
type Interface interface {
// 集合中元素的个数
Len() int
// 判断索引为i的元素和索引为j的元素大小,返回布尔值。如果Less(i, j)和Less(j, i)
// 都返回假, 索引为i的元素和索引为j的元素被认为是相等的。
// Less方法中必须指明判断小于(<)即升序或判断大于(>)即降序。如果Less方法中使用>=或者<=
// 则排序结果中相等的元素按照原始数据顺序输出,否则相等的元素顺序是任意的
Less(i, j int) bool
// 交换索引为i,j的元素位置
Swap(i, j int)
}
下面看例子:
package main
import (
"fmt"
"sort"
)
type student struct {
name string
age int
}
type byAge []student
func (s byAge) Len() int {
return len(s)
}
func (s byAge) Less(i, j int) bool {
return s[i].age < s[j].age
}
func (s byAge) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
students := []student{
{"Amy", 23},
{"John", 27},
{"Jack", 25},
{"Jim", 20},
}
sort.Sort(byAge(students))
fmt.Println(students)
}
// [{Jim 20} {Amy 23} {Jack 25} {John 27}]
针对多维数组的排序,同理。即实现sort.Interface接口,以下示例以二维切片为例
import (
"fmt"
"sort"
)
type multiIntSlice struct {
mSlice [][]int
index int
}
func (s *multiIntSlice) Len() int {
return len(s.mSlice)
}
func (s *multiIntSlice) Swap(i, j int) {
s.mSlice[i], s.mSlice[j] = s.mSlice[j], s.mSlice[i]
}
func (s *multiIntSlice) Less(i, j int) bool {
s1 := s.mSlice[i]
s2 := s.mSlice[j]
index := s.index
return s1[index] < s2[index]
}
func multiSliceSort(s [][]int, index int) [][]int {
if len(s) <= 1 {
return s
}
if index < 0 || index > len(s[0])-1 {
return s
}
multiSlice := &multiIntSlice{mSlice: s, index: index}
sort.Sort(multiSlice)
return multiSlice.mSlice
}
func main() {
mSlice := [][]int{
{1, 3, 6},
{8, 6, 2},
{3, 5, 6},
{9, 2, 1},
}
sortedByColumnOne := multiSliceSort(mSlice, 0)
fmt.Println(sortedByColumnOne)
sortedByColumnTwo := multiSliceSort(mSlice, 1)
fmt.Println(sortedByColumnTwo)
sortedByColumnThree := multiSliceSort(mSlice, 2)
fmt.Println(sortedByColumnThree)
}
// [[1 3 6] [3 5 6] [8 6 2] [9 2 1]]
// [[9 2 1] [1 3 6] [3 5 6] [8 6 2]]
// [[9 2 1] [8 6 2] [1 3 6] [3 5 6]]
