標籤:調用 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