Skip to content

Instantly share code, notes, and snippets.

@ikbear
Created November 8, 2012 12:59
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ikbear/4038654 to your computer and use it in GitHub Desktop.
Save ikbear/4038654 to your computer and use it in GitHub Desktop.
Sort Map(golang)
package main
// sort a map's keys in descending order of its values.
import "sort"
type sortedMap struct {
m map[string]int
s []string
}
func (sm *sortedMap) Len() int {
return len(sm.m)
}
func (sm *sortedMap) Less(i, j int) bool {
return sm.m[sm.s[i]] > sm.m[sm.s[j]]
}
func (sm *sortedMap) Swap(i, j int) {
sm.s[i], sm.s[j] = sm.s[j], sm.s[i]
}
func sortedKeys(m map[string]int) []string {
sm := new(sortedMap)
sm.m = m
sm.s = make([]string, len(m))
i := 0
for key, _ := range m {
sm.s[i] = key
i++
}
sort.Sort(sm)
return sm.s
}
@xlqstar
Copy link

xlqstar commented Jul 22, 2013

您好,不是说map是无序的吗?怎么还可以进行排序??

@srom
Copy link

srom commented Dec 23, 2014

Note that slightly rewriting the Less method as follow ensure a deterministic sorting:

func (sm *sortedMap) Less(i, j int) bool {
    a, b := sm.m[sm.s[i]], sm.m[sm.s[j]]
    if a != b {
        // Order by decreasing value.
        return a > b
    } else {
        // Otherwise, alphabetical order.
        return sm.s[j] > sm.s[i]
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment