go 排序sort的使用


已知一個的struct組成的數組,現在要按照數組中的一個字段排序。python有sort方法,那golang要怎么實現呢?其實golang也有sort方法,並且使用簡單,功能強大。

我們先看一下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)
}

func quickSort(data Interface, a, b, maxDepth int) {
	for b-a > 12 { // Use ShellSort for slices <= 12 elements
		if maxDepth == 0 {
			heapSort(data, a, b)
			return
		}
		maxDepth--
		mlo, mhi := doPivot(data, a, b)
		// Avoiding recursion on the larger subproblem guarantees
		// a stack depth of at most lg(b-a).
		if mlo-a < b-mhi {
			quickSort(data, a, mlo, maxDepth)
			a = mhi // i.e., quickSort(data, mhi, b)
		} else {
			quickSort(data, mhi, b, maxDepth)
			b = mlo // i.e., quickSort(data, a, mlo)
		}
	}
	if b-a > 1 {
		// Do ShellSort pass with gap 6
		// It could be written in this simplified form cause b-a <= 12
		for i := a + 6; i < b; i++ {
			if data.Less(i, i-6) {
				data.Swap(i, i-6)
			}
		}
		insertionSort(data, a, b)
	}
}

通過quickSort方法我們看出,根據數據不同的狀況,quickSort會選擇堆排,快排,插入排中更高效的排序方法,這個我們暫時先不深究,先看如何使用sort.Sort()。

從源碼中我們發現數據data,需要自帶Len,Less,Swap三種方法,所以使用sort.Sort()前,我們需要自己實現Len,Less,Swap來確定按照什么規則排序。

 

來實踐一下,我們先創建一個結構體數組,結構體包含字段Count,我們按照Count對其排序。

package main

import (
    "sort"   
)

type subInfo struct {
	Count  uint   `json:"count"`
}

type SubList []*subInfo

func (p SubList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p SubList) Len() int           { return len(p) }
func (p SubList) Less(i, j int) bool { return p[i].Count > p[j].Count }

func main() {
	st_list := SubList{}
	for i := 0; i < 10; i ++{
		_sub := &subInfo{
			Count:  uint(i),
		}
		st_list = append(st_list, _sub)
	}
	sort.Sort(st_list)
	return
} 

 

需要注意的是,st_list只能初始化成SubList{},而不能初始化為make([]*subInfo, 0),雖然他們結構是一樣的。

最近諸事不順,心煩的一匹,上周也拖更了,總之希望大家事事順心,心愛的人身體健康。

希望對大家有所幫助~


免責聲明!

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



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