Golang对自定义类型排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012050154/article/details/82379385

在实际项目中用到对结构按结构体中的某个字段进行排序,在网上查到一个比较好的办法,mark一下。

首先golang的sort包提供了基本的排序,包括插入排序(insertionSort)、归并排序(symMerge)、堆排序(heapSort)和快速排序(quickSort)。其实现如下

func Sort(data Interface) {
    // Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.
    n := data.Len()
    maxDepth := 0
    for i := n; i > 0; i >>= 1 {
        maxDepth++
    }
    maxDepth *= 2
    quickSort(data, 0, n, maxDepth)
}

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)
}
// 内部实现的四种排序算法
// 插入排序
func insertionSort(data Interface, a, b int)
// 堆排序
func heapSort(data Interface, a, b int)
// 快速排序
func quickSort(data Interface, a, b, maxDepth int)
// 归并排序
func symMerge(data Interface, a, m, b int)

参照sort包对int类型的排序:

// 首先定义了一个[]int类型的别名IntSlice 
type IntSlice []int
// 获取此 slice 的长度
func (p IntSlice) Len() int           { return len(p) }
// 比较两个元素大小 升序
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
// 交换数据
func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
// sort.Ints()内部调用Sort() 方法实现排序
// 注意 要先将[]int 转换为 IntSlice类型 因为此类型才实现了Interface的三个方法 
func Ints(a []int) { Sort(IntSlice(a)) }

可以实现如下代码:

/*
 对结构按其中一个字段排序
 */

type person struct {
	Name string
	Age int
}

type personSlice []person
func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// 按名字或者按年龄排序
//func (s personSlice) Less(i, j int) bool { return s[i].Age > s[j].Age }
func (s personSlice) Less(i, j int) bool { return s[i].Name > s[j].Name }

func main() {
	a := personSlice {
		{
			Name: "AAA",
			Age: 55,
		},
		{
			Name: "BBB",
			Age: 22,
		},
		{
			Name: "CCC",
			Age: 0,
		},
		{
			Name: "DDD",
			Age: 22,
		},
		{
			Name: "EEE",
			Age: 11,
		},
	}
	sort.Stable(a)
	fmt.Println(a)
}

上面仅按结构体中一个字段进行排序,如果想基本多个字段排序呢?答案是利用嵌套结构体实现,即定义基本的Len()和Swap()方法,然后基本嵌套结构封装Less()比较方法。具体如下:

/*
  对结构按多字段排序
 */

type student struct {
	Name string
 	Age int
}

type stus []student
func(s stus) Len() int { return len(s) }
func(s stus) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

type sortByName struct{ stus }
// 按名字排序
func(m sortByName) Less(i, j int) bool {
	return m.stus[i].Name > m.stus[j].Name
}

type sortByAge struct { stus }
// 按年龄排序
func(m sortByAge) Less(i, j int) bool {
	return m.stus[i].Age > m.stus[j].Age
}

func main() {
	s := stus {
		{
			Name:"test123",
			Age:20,
		},
		{
			Name:"test1",
			Age:22,
		},
		{
			Name:"test21",
			Age:21,
		},
	}

	sort.Sort(sortByName{s})
	//sort.Stable(sortByAge{s})
	fmt.Println(s)
}

猜你喜欢

转载自blog.csdn.net/u012050154/article/details/82379385