文章目录
- GoLang之标准库sort包
GoLang之标准库sort包
本文基于Windos系统上Go SDK v1.8进行讲解
1.sort包介绍
2.sort.Interface接口
3.sort.IntSlice切片类型
3.1IntSlice切片类型
3.2Len、Less、Swap、Sort方法
4.sort.Float64Slice切片类型
4.1Float64Slice类型
// Float64Slice implements Interface for a []float64, sorting in increasing order,
// with not-a-number (NaN) values ordered before other values.
type Float64Slice []float64
4.2Len、Less、Swap、Sort方法
func (x Float64Slice) Len() int { return len(x) }
// Less reports whether x[i] should be ordered before x[j], as required by the sort Interface.
// Note that floating-point comparison by itself is not a transitive relation: it does not
// report a consistent ordering for not-a-number (NaN) values.
// This implementation of Less places NaN values before any others, by using:
//
// x[i] < x[j] || (math.IsNaN(x[i]) && !math.IsNaN(x[j]))
//
func (x Float64Slice) Less(i, j int) bool { return x[i] < x[j] || (isNaN(x[i]) && !isNaN(x[j])) }
func (x Float64Slice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
// Sort is a convenience method: x.Sort() calls Sort(x).
func (x Float64Slice) Sort() { Sort(x) }
5.sort.StringSlice切片类型
5.1StringSlice切片类型
// StringSlice attaches the methods of Interface to []string, sorting in increasing order.
type StringSlice []string
5.2Len、Less、Swap、Sort方法
func (x StringSlice) Len() int { return len(x) }
func (x StringSlice) Less(i, j int) bool { return x[i] < x[j] }
func (x StringSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
// Sort is a convenience method: x.Sort() calls Sort(x).
func (x StringSlice) Sort() { Sort(x) }