sort.Sort(xxlist)可對數據集進行排序,如果是自定義的某種數據結構,就需要重寫Len()、Swap()、Less()這三個方法實現如下的Interface接口:
src/sort/sort.go部分源碼
// Sort sorts data.
// It makes one call to data.Len to determine n, and O(n*log(n)) calls to
// data.Less and data.Swap. The sort is not guaranteed to be stable.
func Sort(data Interface) {
n := data.Len()
quickSort(data, 0, n, maxDepth(n))
}
// 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)
}
若直接使用內置的IntSlice、Float64Slice、StringSlice進行對應類型數據的排序,則不需要重寫這三個方法。
實踐如下:
package main
import (
"fmt"
"sort"
)
type Fruit struct {
Name string
Count int
Price float64
}
type fruitList []Fruit
/* 重寫父類Len()、Swap()、Less()三個方法 */
func (list fruitList) Len() int {
return len(list)
}
func (list fruitList) Swap(i, j int) {
list[i], list[j] = list[j], list[i]
}
// 如果index爲i的元素小於index爲j的元素,則返回true,否則返回false
func (list fruitList) Less(i, j int) bool {
return list[i].Price < list[j].Price // 指定按Price屬性、由小到大排序
}
func main() {
/* 1,對自定義結構體進行排序,按哪個字段排序由Less方法決定*/
list := fruitList{
{"蘋果", 2, 3.3},
{"香蕉", 8, 4.55},
{"橘子", 5, 2.5},
{"橙子", 3, 6.05}}
fmt.Println(list)
sort.Sort(list)
fmt.Println(list)
/* 2,以下使用sort包內置好的IntSlice、Float64Slice、StringSlice分別進行排序,
sort.go中已經實現了Len()、Swap()、Less()三個方法,因此自己不用再實現直接使用 */
// 對自定義int類型數組以內置的IntSlice進行排序
arr := []int{2, 1, 6, 5, 3}
intList := sort.IntSlice(arr)
fmt.Println(intList)
sort.Sort(intList)
fmt.Println(intList)
// 對自定義的float64類型的數組以Float64Slice進行排序
arr1 := []float64{3.1415926935, 2.101, 7.999, 5.01}
float64List := sort.Float64Slice(arr1)
fmt.Println(float64List)
sort.Sort(float64List)
fmt.Println(float64List)
// 對自定義的string類型的數組進行排序
strList := sort.StringSlice{"bc", "ac", "abd"}
fmt.Println(strList)
sort.Sort(strList)
fmt.Println(strList)
}
控制檯:
[{蘋果 2 3.3} {香蕉 8 4.55} {橘子 5 2.5} {橙子 3 6.05}]
[{橘子 5 2.5} {蘋果 2 3.3} {香蕉 8 4.55} {橙子 3 6.05}]
[2 1 6 5 3]
[1 2 3 5 6]
[3.1415926935 2.101 7.999 5.01]
[2.101 3.1415926935 5.01 7.999]
[bc ac abd]
[abd ac bc]
Process finished with exit code 0