go sort包排序用法

sort.Sort(xxlist)可对数据集进行排序,如果是自定义的某种数据结构,就需要重写Len()、Swap()、Less()这三个方法实现如下的Interface接口:

src/sort/sort.go部分源码

// Sort sorts data.
// 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))
}

// 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)
}

若直接使用内置的IntSlice、Float64Slice、StringSlice进行对应类型数据的排序,则不需要重写这三个方法。

实践如下:

package main

import (
	"fmt"
	"sort"
)

type Fruit struct {
	Name  string
	Count int
	Price float64
}

type fruitList []Fruit

/* 重写父类Len()、Swap()、Less()三个方法 */
func (list fruitList) Len() int {
	return len(list)
}

func (list fruitList) Swap(i, j int) {
	list[i], list[j] = list[j], list[i]
}

// 如果index为i的元素小于index为j的元素,则返回true,否则返回false
func (list fruitList) Less(i, j int) bool {
	return list[i].Price < list[j].Price // 指定按Price属性、由小到大排序
}

func main() {
	/* 1,对自定义结构体进行排序,按哪个字段排序由Less方法决定*/
	list := fruitList{
		{"苹果", 2, 3.3},
		{"香蕉", 8, 4.55},
		{"橘子", 5, 2.5},
		{"橙子", 3, 6.05}}
	fmt.Println(list)
	sort.Sort(list)
	fmt.Println(list)

	/* 2,以下使用sort包内置好的IntSlice、Float64Slice、StringSlice分别进行排序,
	sort.go中已经实现了Len()、Swap()、Less()三个方法,因此自己不用再实现直接使用 */
	// 对自定义int类型数组以内置的IntSlice进行排序
	arr := []int{2, 1, 6, 5, 3}
	intList := sort.IntSlice(arr)
	fmt.Println(intList)
	sort.Sort(intList)
	fmt.Println(intList)

	// 对自定义的float64类型的数组以Float64Slice进行排序
	arr1 := []float64{3.1415926935, 2.101, 7.999, 5.01}
	float64List := sort.Float64Slice(arr1)
	fmt.Println(float64List)
	sort.Sort(float64List)
	fmt.Println(float64List)

	// 对自定义的string类型的数组进行排序
	strList := sort.StringSlice{"bc", "ac", "abd"}
	fmt.Println(strList)
	sort.Sort(strList)
	fmt.Println(strList)

}

控制台:

[{苹果 2 3.3} {香蕉 8 4.55} {橘子 5 2.5} {橙子 3 6.05}]
[{橘子 5 2.5} {苹果 2 3.3} {香蕉 8 4.55} {橙子 3 6.05}]
[2 1 6 5 3]
[1 2 3 5 6]
[3.1415926935 2.101 7.999 5.01]
[2.101 3.1415926935 5.01 7.999]
[bc ac abd]
[abd ac bc]

Process finished with exit code 0
发布了189 篇原创文章 · 获赞 144 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/HYZX_9987/article/details/105184971