Created
February 7, 2021 14:38
-
-
Save martinusso/6e2ac626cd9b07e3fa96206d6eb490d0 to your computer and use it in GitHub Desktop.
sort and reverse map by values - 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
// A slice of pairs that implements sort.Interface to sort and reverse by values | |
type PairList []Pair | |
func (p PairList) Len() int { return len(p) } | |
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } | |
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value } | |
func sortMapByValues(m map[string]float64) PairList { | |
p := make(PairList, len(m)) | |
i := 0 | |
for k, v := range m { | |
p[i] = Pair{k, v} | |
i++ | |
} | |
sort.Sort(p) | |
return p | |
} | |
func reverseMapByValues(m map[string]float64) PairList { | |
p := make(PairList, len(m)) | |
i := 0 | |
for k, v := range m { | |
p[i] = Pair{k, v} | |
i++ | |
} | |
sort.Sort(sort.Reverse(p)) | |
return p | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment