# Go简单排序

Rhino(犀牛) · · 5897 次点击 · · 开始浏览

``````package main
import (
"fmt"
"sort"
)
func main()
m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
mk := make([]string, len(m))
i := 0
for k, _ := range m {
mk[i] = k
i++
}
sort.SortStrings(mk)
fmt.Println(mk)
}
``````

``````// A data structure to hold a key/value pair.
type Pair struct {
Key   string
Value int
}

// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }

// A function to turn a map into a PairList, then sort and return it.
func sortMapByValue(m map[string]int) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
}
sort.Sort(p)
return p
}
``````

1 回复  |  直到 2020-02-18 17:34:13

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

``````package main
import (
"fmt"
"sort"
)
func main()
m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
mk := make([]string, len(m))
i := 0
for k, _ := range m {
mk[i] = k
i++
}
sort.SortStrings(mk)
fmt.Println(mk)
}
``````

``````// A data structure to hold a key/value pair.
type Pair struct {
Key   string
Value int
}

// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }

// A function to turn a map into a PairList, then sort and return it.
func sortMapByValue(m map[string]int) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
}
sort.Sort(p)
return p
}
``````