1、基础类型排序

官方package: sort, 提供了对int,float,string的排序

  • sort.Ints
  • sort.Floats
  • sort.Strings
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
ints := []int{5, 6, 1, 2, 3} // unsorted
sort.Ints(ints)
fmt.Println(ints)
sort.Sort(sort.Reverse(sort.IntSlice(ints))) // sorted descending
fmt.Println(ints)

floats := []float64{1.3, 3.2, 2.2} // unsorted
sort.Float64s(floats)              // sorted ascending
fmt.Println(floats)
sort.Sort(sort.Reverse(sort.Float64Slice(floats))) // sorted descending
fmt.Println(floats) 

strings := []string{"b", "a", "b1", "1"} // unsorted
sort.Strings(strings)
fmt.Println(strings)
sort.Sort(sort.Reverse(sort.StringSlice(strings))) // sorted descending
fmt.Println(strings)

2、使用自定义的排序函数

1
2
3
  func SliceStable(slice interface{}, less func(i, j int) bool)
  
  func Slice(slice interface{}, less func(i, j int) bool)

sort.Slice使用function less(i, j int) bool 来对slice进行排序。

sort.SclieStabl使用function less(i, j int)bool对slice进行排序,当遇到遇到相等的元素时,将会保持原来的顺序不变。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
people := []struct {
	Name string
	Age  int
}{
	{"Alice", 25},
	{"Elizabeth", 75},
	{"Alice", 75},
	{"Bob", 75},
	{"Alice", 75},
	{"Bob", 25},
	{"Colin", 25},
	{"Elizabeth", 25},
}
// Sort by name, preserving original order
sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)

// Sort by age preserving name order
sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age,name:", people)

3、对自定义struct进行排序

1
2
3
4
5
6
7
8
9
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)
}

如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
type Person struct {
    Name string
    Age  int
}

// ByAge implements sort.Interface based on the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    family := []Person{
        {"Alice", 23},
        {"Eve", 2},
        {"Bob", 25},
    }
    sort.Sort(ByAge(family))
    fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]
}

更多:

https://golang.org/pkg/sort/