天天看點

map 排序_Go語言中的排序

map 排序_Go語言中的排序

對一片int,float64或字元串進行排序

s := []int{4, 2, 3, 1}
sort.Ints(s)
fmt.Println(s) // [1 2 3 4]
           

使用自定義比較器排序

使用該功能sort.Slice。它使用提供的函數對切片進行排序less(i, j int) bool。

要在保持相等元素的原始順序的同時對切片進行排序,請sort.SliceStable改為使用。

family := []struct {
    Name string
    Age  int
}{
    {"Alice", 23},
    {"David", 2},
    {"Eve", 2},
    {"Bob", 25},
}


sort.SliceStable(family, func(i, j int) bool {
    return family[i].Age < family[j].Age
})
fmt.Println(family) 
// [{David 2} {Eve 2} {Alice 23} {Bob 25}]
           

排序自定義資料結構

使用通用sort.Sort和 sort.Stable函數。

它們對實作接口的任何集合進行排序 。sort.Interface

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)
}
這是一個例子。

type Person struct {
    Name string
    Age  int
}

// ByAge implements sort.Interface based on the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    family := []Person{
        {"Alice", 23},
        {"Eve", 2},
        {"Bob", 25},
    }
    sort.Sort(ByAge(family))
    fmt.Println(family) 
    // [{Eve 2} {Alice 23} {Bob 25}]
}
           

按鍵或值對map排序

一個map是一個無序的鍵-值對的集合。如果需要穩定的疊代順序,則必須維護單獨的資料結構。

此代碼示例使用一個鍵片段按鍵順序對映射進行排序。

m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}

keys := make([]string, 0, len(m))
for k := range m {
    keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
    fmt.Println(k, m[k])
}
// Output:
// Alice 2
// Bob 3
// Cecil 1