-
-
Save bernardolm/f0e1cec2961b06612d3be502c762ed72 to your computer and use it in GitHub Desktop.
Sort Map(golang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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