golang 的排序sort

來源:互聯網
上載者:User

標籤:調用   Golan   less   quicksort   quick   port   lang   heap   epo   

首先看一下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 mainimport (    "sort"    "fmt")type person struct {    Name string    Age int}type personSlice []personfunc (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!

golang 的排序sort

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.