Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go排序实例
Go排序实例
作者:--    发布时间:2019-11-20

go语言的 sort 包实现了内置和用户定义类型的排序。我们先看看内置的排序。排序方法特定于内置类型; 这里是一个字符串的例子。 请注意,排序是就地排序,因此它会更改给定的切片,并且不返回新的切片。

这里例举一个排序int类型数值的一个例子。

也可以使用sort来检查切片是否已经按照排序顺序。

运行程序打印排序的字符串,以及int数据值和true作为aresorted测试的结果。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

sorting.go的完整代码如下所示 -

package main

import "fmt"
import "sort"

func main() {

    // sort methods are specific to the builtin type;
    // here's an example for strings. note that sorting is
    // in-place, so it changes the given slice and doesn't
    // return a new one.
    strs := []string{"c", "a", "b"}
    sort.strings(strs)
    fmt.println("strings:", strs)

    // an example of sorting `int`s.
    ints := []int{7, 2, 4}
    sort.ints(ints)
    fmt.println("ints:   ", ints)

    // we can also use `sort` to check if a slice is
    // already in sorted order.
    s := sort.intsaresorted(ints)
    fmt.println("sorted: ", s)
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run sorting.go
strings: [a b c]
ints:    [2 4 7]
sorted:  true

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册