Go语言中的排序

排序作为程序中最常用的功能之一,各种编程语言也都通过类库提供了现成的排序工具,在golang中就是sort包。
并不是所有的东西都能够被排序,通常能够被排序的对象需要具有以下三个特征:

  1. 是一个有限元素的集合
  2. 集合中的元素可以交换相对位置
  3. 集合中任意两个元素能够相互比较大小

sort包定义了Interface接口来体现上述的三个特征。

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	// Less reports whether the element with
	// index i should sort before the element with index j.
	Less(i, j int) bool
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

sort包提供了func Sort(data Interface)函数。所有实现了sort.Interface的对象都能够通过这个函数来排序。比如下面的例子对一个时间数组进行排序:

type sortableTimeArray []time.Time

func (a sortableTimeArray) Len() int {
	return a.Len()
}
func (a sortableTimeArray) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}
func (a sortableTimeArray) Less(i, j int) bool {
	return a[i].Unix() < a[j].Unix()
}
func main() {
	var a sortableTimeArray
	sort.Sort(a)
}

对于一些常用的类型(整数、浮点数、字符串),sort包直接提供了可排序的集合类型,和排序函数,不需要再去额外实现上面三个方法。

type IntSlice []int
type Float64Slice []float64
type StringSlice []string

func Ints(a []int)           //整数排序
func Float64s(a []float64)   //浮点数排序
func Strings(a []string)     //字符串排序
var a sort.IntSlice = []int{3, 2, 4, 1}
sort.Sort(a)
fmt.Println(a)      //output: [1 2 3 4]

或者

a := []int{3, 2, 4, 1}
sort.Ints(a) 
fmt.Println(a)      //output: [1 2 3 4]

此外,sort包还提供了其它一些排序相关的函数方便使用,比如

func Reverse(data Interface) Interface //反向排序
func Stable(data Interface)            //稳定排序
//检查是否有序
func IsSorted(data Interface) bool    
func IntsAreSorted(a []int) bool
func Float64sAreSorted(a []float64) bool
func StringsAreSorted(a []string) bool

对于slice来说,无论元素是什么类型,Len()和Swap()的逻辑都是固定的,只需要提供比较方式即可:

// Slice sorts the provided slice given the provided less function.
func Slice(slice interface{}, less func(i, j int) bool)

// SliceStable sorts the provided slice given the provided less
func SliceStable(slice interface{}, less func(i, j int) bool)

// SliceIsSorted tests whether a slice is sorted.
func SliceIsSorted(slice interface{}, less func(i, j int) bool)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值