Golang對自定義型別排序

2021-08-27 03:06:24 字數 1990 閱讀 3798

在實際專案中用到對結構按結構體中的某個字段進行排序,在網上查到乙個比較好的辦法,mark一下。

首先golang的sort包提供了基本的排序,包括插入排序(insertionsort)、歸併排序(symmerge)、堆排序(heapsort)和快速排序(quicksort)。其實現如下

func sort(data inte***ce) 

maxdepth *= 2

quicksort(data, 0, n, maxdepth)

}type inte***ce inte***ce

// 內部實現的四種排序演算法

// 插入排序

func insertionsort(data inte***ce, a, b int)

// 堆排序

func heapsort(data inte***ce, a, b int)

// 快速排序

func quicksort(data inte***ce, a, b, maxdepth int)

// 歸併排序

func symmerge(data inte***ce, a, m, b int)

參照sort包對int型別的排序:

// 首先定義了乙個int型別的別名intslice 

type intslice int

// 獲取此 slice 的長度

func (p intslice) len() int

// 比較兩個元素大小 公升序

func (p intslice) less(i, j int) bool

// 交換資料

func (p intslice) swap(i, j int)

// sort.ints()內部呼叫sort() 方法實現排序

// 注意 要先將int 轉換為 intslice型別 因為此型別才實現了inte***ce的三個方法

func ints(a int)

可以實現如下**:

/*

對結構按其中乙個字段排序

*/type person struct

type personslice person

func (s personslice) len() int

func (s personslice) swap(i, j int)

// 按名字或者按年齡排序

//func (s personslice) less(i, j int) bool

func (s personslice) less(i, j int) bool

func main() ,

, ,

, ,

} sort.stable(a)

fmt.println(a)

}

上面僅按結構體中乙個字段進行排序,如果想基本多個字段排序呢?答案是利用巢狀結構體實現,即定義基本的len()和swap()方法,然後基本巢狀結構封裝less()比較方法。具體如下:

/*

對結構按多字段排序

*/type student struct

type stus student

func(s stus) len() int

func(s stus) swap(i, j int)

type sortbyname struct

// 按名字排序

func(m sortbyname) less(i, j int) bool

type sortbyage struct

// 按年齡排序

func(m sortbyage) less(i, j int) bool

func main() ,

, ,

} sort.sort(sortbyname)

fmt.println(s)

}

golang 自定義型別

1.8 自定義型別 可將型別分為命名和未命名兩 大類。命名型別包括 bool int string 等,而 array slice map 等和具體元素型別 長度等有關,屬於未命名型別。具有相同宣告的未命名型別被視為同 一型別。具有相同基型別的指標。具有相同元素型別和 長度的 array。具有相同元...

sort自定義型別排序

乙個很簡單的問題,不過也磨了我好一會,在些總結記錄。1.對於不用寫自定義資料結構的情況 static int cmp const pair x,const pair y if x.second y.second return x.second y.second else return x.first...

C 自定義型別排序

在編寫程式處理資料時經常需要對自己組織的資料進行排序,有時還是不同形式的排序,在c 中可以自定義結構體重載bool operator函式,也可以自己寫int compare 而在c 中自定義排序,就需要對類的icomparer 介面進行實現,排序時呼叫sort 方法時將實現的排序介面作為引數傳入即可...