GoLang标准库的sort包提供了排序切片和用户自定义数据集以及相关功能的函数。
Sort操作的对象通常是一个slice,需要满足三个基本的接口,并且能够使用整数来索引。
1.sort实现原理
Sort排序的函数原型如下所示:
1.1 Sort
// It makes one call to data.Len to determine n, and O(n*log(n)) calls to
// data.Less and data.Swap. The sort is not guaranteed to be stable.
func Sort(data Interface) {
n := data.Len()
quickSort(data, 0, n, maxDepth(n))
}
1.2 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)
}
1.3 quickSort
func quickSort(data Interface, a, b, maxDepth int) {
for b-a > 12 {
// Use ShellSort for slices <= 12 elements
if maxDepth == 0 {
heapSort(data, a, b)
return
}
maxDepth--
mlo, mhi := doPivot(data, a, b)