Created
November 8, 2012 12:59
-
-
Save ikbear/4038654 to your computer and use it in GitHub Desktop.
Sort Map(golang)
This file contains hidden or 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 | |
} |
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
您好,不是说map是无序的吗?怎么还可以进行排序??