go语言从例子开始之Example38.排序

Go 的 sort 包实现了内置和用户自定义数据类型的排序功能。我们首先关注内置数据类型的排序。

Example:

package main
import (
    "fmt"
    "sort"
)


func main() {
    //排序方法是正对内置数据类型的;这里是一个字符串的例子。
    // 注意排序是原地更新的,所以他会改变给定的序列并且不返回一个新值
    strarr := []string{"f", "d", "a", "h"}
    sort.Strings(strarr)
    fmt.Println("Strings:", strarr)

    //int型排序
    intarr := []int{6, 7, 1, 3}
    sort.Ints(intarr)
    fmt.Println("Ints:", intarr)

    //检查数组是否已经排好序,s已排序true, 否则false
    s := sort.IntsAreSorted(intarr)
    fmt.Println("Sorted:", s)

      a := sort.StringsAreSorted(strarr)
      fmt.Println("Sorted:", a)

}

Result:

$ go run example.go
Strings: [a d f h]
Ints: [1 3 6 7]
Sorted: true

Sorted: true

坐标: 上一个例子   下一个例子

原文地址:https://www.cnblogs.com/yhleng/p/11772379.html