go语言-golang基础-sort使用方法

sort 包 在内部实现了四种基本的排序算法:插入排序(insertionSort)、归并排序(symMerge)、堆排序(heapSort)和快速排序(quickSort);sort包会依据实际数据自动选择最优的排序算法。所以我们写代码时只需要考虑实现 sort.Interface 这个类型就可以了。

1. 对 []int 和 []string字符串进行排序

package main

import (
    "fmt"
    "sort"
)

func main() {
    // []int排序
    nums := []int{2, 31, 5, 6, 3}
    //顺序
    sort.Ints(nums)
    fmt.Println("1: ", nums)
    //使用 sort.Reverse 进行逆序排序
    sort.Sort(sort.Reverse(sort.IntSlice(nums)))
    fmt.Println("2: ", nums)

    // []string字符串排序
    names := []string{"abc", "12", "kk", "Jordan", "Ko", "DD"}
    // 顺序
    sort.Strings(names)
    fmt.Println("3: ", names)
    // 逆序
    sort.Sort(sort.Reverse(sort.StringSlice(names)))
    fmt.Printf("4: After Reverse: %#v\n", names)

    //查找
    // [0,100)
    // 二分查找
    nums = []int{1, 3, 5, 7, 9}
    fmt.Println("5: ", nums[sort.SearchInts(nums, 8)] == 8)
    fmt.Println("6: ", nums[sort.SearchInts(nums, 5)] == 5)

}
/*
$ go run sort.go
1:  [2 3 5 6 31]
2:  [31 6 5 3 2]
3:  [12 DD Jordan Ko abc kk]
4: After Reverse: []string{"kk", "abc", "Ko", "Jordan", "DD", "12"}
5:  false
6:  true

*/

2. 使用 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)

}

结果:

$ go run sort-detail.go
[{CCC 0} {EEE 11} {BBB 22} {DDD 22} {AAA 55}]