golang 的排序sort

首先看一下sort包的原理

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

 

最后自己写一个例子

 

package main

import (
    "sort"
    "fmt"
)
type person struct {
    Name string
    Age int
}

type personSlice []person

// 这三个方法必须有,相当于实现了sort.Interface 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 main() { a := personSlice { { Name: "AAA", Age: 55, }, { Name: "BBB", Age: 22, }, { Name: "CCC", Age: 0, }, { Name: "DDD", Age: 22, }, { Name: "EEE", Age: 11, }, } sort.Sort(a) fmt.Println(a) }

 

ok!

posted @ 2018-08-22 11:30  天之草  阅读(5425)  评论(0编辑  收藏  举报