|
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 切片是否已经按升序排列。
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, c[j] = c[j], c
}
func (c IntSlice) Less(i, j int) bool {
return c < c[j]
}
func main() {
a := IntSlice{1, 3, 5, 7, 2}
b := []float64{1.1, 2.3, 5.3, 3.4}
c := []int{1, 3, 5, 4, 2}
fmt.Println(sort.IsSorted(a)) //false
if !sort.IsSorted(a) {
sort.Sort(a)
}
if !sort.Float64sAreSorted(b) {
sort.Float64s(b)
}
if !sort.IntsAreSorted(c) {
sort.Ints(c)
}
fmt.Println(a)//[1 2 3 5 7]
fmt.Println(b)//[1.1 2.3 3.4 5.3]
fmt.Println(c)// [1 2 3 4 5]
}
func Search(n int, f func(int) bool) int
search使用二分法进行查找,Search()方法回使用“二分查找”算法来搜索某指定切片[0:n],并返回能够使f(i)=true的最小的i(0 |
|
|