【问题标题】:How to sort a map[int]int by its values? [duplicate]如何按其值对 map[int]int 进行排序? [复制]
【发布时间】:2018-05-24 04:36:02
【问题描述】:

我的插入和快速排序不适用于 map[uint64]uint64 值。任何人都可以帮忙吗?提前致谢。希望按值排序地图“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
}

【问题讨论】:

  • 这甚至不会构建。请显示一个包含minimal, complete, and verifiable example
  • 一个 golang 映射,它只是一个哈希表,根据定义是无序的。您无法对它实际保存的数据进行排序。充其量,您可以创建一个由实际映射和一个包含键的切片组成的包装器类型,并对切片进行排序。然后,当您迭代地图时,您实际上会迭代有序切片并以设定的顺序从地图中检索数据。这实现起来相当简单,但我不禁觉得您正在尝试在这里解决 X-Y 问题。你想做什么?也许有更好的方法

标签: sorting go slice quicksort


【解决方案1】:

Go 地图是无序的数据结构。无论您做什么,它都不会按键或按值排序。

如果您想对值进行排序,您应该使用切片并对其执行快速排序。

请参阅Go spec 或Effective Go 了解更多详情。

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多