终于将VS Code的Golang开发环境配置完成。
golang中实现了排序算法的sort包.
sort包中实现了3种基本的排序算法:插入排序.快排和堆排序.和其他语言中一样,这三种方式都是不公开的,他们只在sort包内部使用.所以用户在使用sort包进行排序时无需考虑使用那种排序方式,sort.Interface定义的三个方法:获取数据集合长度的Len()方法、比较两个元素大小的Less()方法和交换两个元素位置的Swap()方法,就可以顺利对数据集合进行排序。sort包会根据实际数据自动选择高效的排序算法。
type Interface
type Interface interface { Len() int // Len 为集合内元素的总数 Less(i, j int) bool //如果index为i的元素小于index为j的元素,则返回true,否则返回false Swap(i, j int) // Swap 交换索引为 i 和 j 的元素 }
任何实现了 sort.Interface 的类型(一般为集合),均可使用该包中的方法进行排序。这些方法要求集合内列出元素的索引为整数。
func Float64s(a []float64) //Float64s将类型为float64的slice a以升序方式进行排序
func Float64sAreSorted(a []float64) bool //判定是否已经进行排序func Ints(a []int)
func Ints(a []int) //Ints 以升序排列 int 切片。
func IntsAreSorted(a []int) bool //IntsAreSorted 判断 int 切片是否已经按升序排列。
func IsSorted(data Interface) bool IsSorted 判断数据是否已经排序。包括各种可sort的数据类型的判断.
func Strings(a []string)//Strings 以升序排列 string 切片。
func StringsAreSorted(a []string) bool//StringsAreSorted 判断 string 切片是否已经按升序排列。
// sorttest
package main
import (
"fmt"
"sort"
)
// 定义interface{},并实现sort.Interface接口的三个方法,通过这三个接口方法可以对排序进行设置
type IntSlice []int
func (c IntSlice) Len() int {
return len(c)
}
func (c IntSlice) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
func (c IntSlice) Less(i, j int) bool {
return c[i] < c[j]
}
func main() {
a := IntSlice{2, 4, 3, 1, 6, 9, 5, 0, 8, 7}
b := []int{2, 4, 3, 1, 6, 9, 5, 0, 8, 7}
c := []float64{1.1, 2.2, 3.1, 1.8, 9.9}
sort.Sort(a)
sort.Ints(b)
sort.Float64s(c)
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[1.1 1.8 2.2 3.1 9.9]