
1、默认排序
使用sort包进行排序。排序是就地排序,因此它会更改给定的切片,并且不返回新的切片。
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{, , }
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)
}
执行上面代码,将得到以下输出结果
Strings: [a b c]
Ints: [ ]
Sorted: true
从上述代码可知,排序不同类型切片,调用不同接口,排序时直接对参数进行修改,排序接口不对排序后切片进行返回。
2、自定义排序
自定义排序需要我们声明一个相应类型,并实现sort.Interface-Len,Less,Swap在这个类型上,Less接口是正真的排序方法,Swap用于交换两个值,Len用于求出切片大小。如下示例代码,首先将原始 fruits
切片转换为ByLength
来实现自定义排序,然后对该类型切片使用sort.Sort()
方法。
图1 sort.Interface定义
其实自定义排序就是对接口的使用。针对ByLength结构重写了sort.Interface接口的方法。如图1所示,是在LiteIDE中sort.Interface的提示
package main import "sort"
import "fmt" // In order to sort by a custom function in Go, we need a
// corresponding type. Here we've created a `ByLength`
// type that is just an alias for the builtin `[]string`
// type.
type ByLength []string // We implement `sort.Interface` - `Len`, `Less`, and
// `Swap` - on our type so we can use the `sort` package's
// generic `Sort` function. `Len` and `Swap`
// will usually be similar across types and `Less` will
// hold the actual custom sorting logic. In our case we
// want to sort in order of increasing string length, so
// we use `len(s[i])` and `len(s[j])` here.
func (s ByLength) Len() int {
return len(s)
}
func (s ByLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByLength) Less(i, j int) bool {
return len(s[i]) < len(s[j])
} // With all of this in place, we can now implement our
// custom sort by casting the original `fruits` slice to
// `ByLength`, and then use `sort.Sort` on that typed
// slice.
func main() {
fruits := []string{"peach", "banana", "kiwi"}
sort.Sort(ByLength(fruits))
fmt.Println(fruits)
}
执行上面代码,将得到以下输出结果
[kiwi peach banana]