Skip to content

Instantly share code, notes, and snippets.

@rafaeljesus
Forked from ikbear/sortmap.go
Created January 29, 2017 13:17
Show Gist options
  • Save rafaeljesus/4343c3d272e20e8c1804b495e10b50c0 to your computer and use it in GitHub Desktop.
Save rafaeljesus/4343c3d272e20e8c1804b495e10b50c0 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment