Go語言的 sort 包實現(xiàn)了內(nèi)置和用戶定義類型的排序。我們先看看內(nèi)置的排序。排序方法特定于內(nèi)置類型; 這里是一個字符串的例子。 請注意,排序是就地排序,因此它會更改給定的切片,并且不返回新的切片。
這里例舉一個排序int類型數(shù)值的一個例子。
也可以使用sort來檢查切片是否已經(jīng)按照排序順序。
運行程序打印排序的字符串,以及int數(shù)據(jù)值和true作為AreSorted測試的結(jié)果。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.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)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run sorting.go
Strings: [a b c]
Ints: [2 4 7]
Sorted: true