# 使用golang的sort包进行排序

golang和java等语言一样，系统自带了一个排序方法，可以快速实现排序。废话不多说，先上栗子，再解释。

package main

import (
"fmt"
"math/rand"
"sort"
"strconv"
)

func main() {
oneArr := make([]*One, 10)
for i := 0; i < 10; i++ {
oneArr[i] = &One{
Name: "name" + strconv.FormatInt(int64(i), 10),
Num:  rand.Intn(1000),
}
}

for _, v := range oneArr {
fmt.Print(v, " ")
}
fmt.Println()
sort.Sort(OneList(oneArr))
for _, v := range oneArr {
fmt.Print(v, " ")
}
fmt.Println()

}

type One struct {
Num  int
Name string
}

type OneList []*One

func (this OneList) Len() int {
return len(this)
}
func (this OneList) Less(i, j int) bool {
return this[i].Num < this[j].Num
}
func (this OneList) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}

## 运行结果

// 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)
}

• Len()
函数 返回要排序的序列的长度
• Less()
函数 返回排序需要的比较的规则，如果符合这个规则，就进行交换
• Swap()
函数 进行排序的交换规则

OneList

，随机填充数据，然后调用 sort

Sort()

sort

## 拓展

golang的 sort

type IntSlice []int
type Float64Slice []float64
type StringSlice []string


package main

import (
"fmt"
"math/rand"
"sort"
)

func main() {
one := make([]int, 10)
for i := 0; i < 10; i++ {
one[i] = int(rand.Int31n(1000))
}
fmt.Println(one)
sort.Sort(sort.IntSlice(one))
fmt.Println(one)

}