golang标准库中的sort包

一、sort包的内容,以及使用
sort包提供了排序切片和用户自定义数据集以及相关功能的函数。

sort包主要针对[]int、[]float64、[]string、以及其他自定义切片的排序。
接口

func Interface interface

结构体

type IntSlice struct
type Float64Slice
type StringSlice

函数

func Ints(a []int)
func IntsAreSorted(a []int) bool
func SearchInts(a []int, x int) int
func Float64s(a []float64)
func Float64sAreSorted(a []float64) bool
func SearchFloat64s(a []float64, x float64) int
func SearchFloat64s(a []flaot64, x float64) bool
func Strings(a []string)
func StringsAreSorted(a []string) bool
func SearchStrings(a []string, x string) int
func Sort(data Interface)
func Stable(data Interface)
func Reverse(data Interface) Interface
func ISSorted(data Interface) bool
func Search(n int, f func(int) bool) int

1)接口 type Interface

type Interface interface {
    Len() int           // Len方法返回集合中的元素个数
    Less(i, j int) bool // i>j,该方法返回索引i的元素是否比索引j的元素小、
    Swap(i, j int)      // 交换i, j的值
}

代码案例

package main

import (
    "fmt"
    "sort"
)

type NewInts []uint

func (n NewInts) Len() int {
    return len(n)
}

func (n NewInts) Less(i, j int) bool {
    fmt.Println(i, j, n[i] < n[j], n)
    return n[i] < n[j]
}

func (n NewInts) Swap(i, j int) {
    n[i], n[j] = n[j], n[i]
}

func main() {
    n := []uint{1,3,2}
    sort.Sort(NewInts(n))
    fmt.Println(n)
}

/*
输出:
1 0 false [1 3 2]
2 1 true [1 3 2]
1 0 false [1 2 3]
[1 2 3]
 */

从上面这个案例可以知道,在Less方法里面i > j,如果这个方法返回true,则会执行Swap方法。
根据这个结论,我们可以实现一些我们想要实现的排序功能。

2)结构体
三种结构体的方法都是一样的,只是分别针对int切片、float64切片、strings切片这三种不同的类型。
然后三种结果都有五个公开方法
1)

func (p xxxSlice) Len() int  // 切片长度
func (p xxxSlice) Less(i, j int) bool
func (p xxxSlice) Swap(i, j int)
func (p xxxSlice) Search(x xxx) int
// 这个和后面那个功能一样
func (p xxxSlice) Sort()  

函数
1)func xxxs(a []xxx)
对[]int、[]float64、[]string三种类型变量进行排序
2)func xxxsAreSorted(a []xxx] bool
判断[]int、[]float64、[]string三种类型变量是否排序了
3)func Serchxxxs(a []xxx, x xxx) int
查找x插入之后会被插入的位置
4)func Sort(data Interface)
对实现接口的数据类型变量进行排序。它调用一次data.Len来决定排序的长度n,调用data.Less和data.Swap的开销为O(n*log(n))。此排序为不稳定排序。它根据不同形式决定使用不同的排序方式(插入排序、堆排序、快排)
5)func Stable(data Interface)
Stable对data进行排序,不过排序过程中,如果data中存在相等的元素,则它们原来的顺序不会改变,是一种稳定的排序。
6)func Reverse(data Interface) Interface
使用sort.Reverse结合sort.Sort进行逆排序,实现原来相反的排序。
代码案例

package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{1, 2, 5, 3, 4}
    fmt.Println(a)        // [1 2 5 3 4]
    sort.Sort(sort.Reverse(sort.IntSlice(a)))
    fmt.Println(a)        // [5 4 3 2 1]
}

7)func IsSorted(data Interface) bool
判断data是否已经排序好了

8)func Search(n int, f func(int) bool) int
Search使用二分法进行查找,Search()方法会使用"二分查找"算法来搜索某指定切片[0:n],并返回能够f(i)=true的最小的i(0<=i

你可能感兴趣的:(golang标准库中的sort包)