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!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM