This question already has answers here:
How to sort a Map[string]int by its values?

(7个答案)


2年前关闭。




我的插入和快速排序不适用于map [uint64] uint64值。有人可以帮忙吗?提前致谢。希望按值排序 map “aint”。

请询问详细信息(如果有)。我将改善这个问题。再次感谢。
package main

import (
    "sort"
    "fmt"
    "time"
    "runtime"
    "math/rand"
)
    func main() {

    runtime.GOMAXPROCS(runtime.NumCPU())
    start := time.Now()

    //the map variable
    aint := map[uint64]uint64{}

    start = time.Now()
    for i := uint64(0); i < 100000000; i++ {
            aint[i+32132112313] = uint64(rand.Intn(13123123123)+2312423213) //random generation of input data
//              aint = insertSort(aint,uint64(rand.Intn(13123123123)))
    }
    fmt.Printf("%d\n", aint[22] )

    elapsed := time.Since(start)
    fmt.Printf("Entry took %s %d\n", elapsed)

    start = time.Now()
    quicksort(aint)

    //      sort.Sort(sort.IntSlice(aint))

    elapsed = time.Since(start)
    fmt.Printf("Sorting took %s %d\n", elapsed)
}
func insertionsort(items []int) {
    var n = len(items)
    for i := 1; i < n; i++ {
            j := i
            for j > 0 {
                    if items[j-1] > items[j] {
                            items[j-1], items[j] = items[j], items[j-1]
                    }
                    j = j - 1
            }
    }
}


func quicksort(a map[uint64]uint64) map[uint64]uint64 {
    if len(a) < 2 {
            return a
    }

    left, right := uint64(0), uint64(len(a)-1)

    pivot := Uint64() % uint64(len(a))

    a[pivot], a[right] = a[right], a[pivot]
    // does not work anymore from here onwards.
    for uint64(i), _ := range a {
            if a[i] < a[right] {
                    a[left], a[i] = a[i], a[left]
                    left++
            }
    }

    a[left], a[right] = a[right], a[left]

    quicksort(a[:left])
    quicksort(a[left+1:])

    return a
}

最佳答案

Go map 是无序的数据结构。无论您做什么,都不会按键或值对其进行排序。

如果要对值进行排序,则应使用 slice 并对其进行快速排序。

有关更多详细信息,请参见Go specEffective Go

07-24 09:44
查看更多