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