golang sort包 排序

时间:2024-11-04 12:37:26

[]float64:

ls := sort.Float64Slice{
1.1,
4.4,
5.5,
3.3,
2.2,
}
fmt.Println(ls) //[1.1 4.4 5.5 3.3 2.2]
sort.Float64s(ls)
fmt.Println(ls) //[1.1 2.2 3.3 4.4 5.5]

[]int:

ls := sort.IntSlice{
,
,
,
,
,
}
fmt.Println(ls) //[1 4 5 3 2]
sort.Ints(ls)
fmt.Println(ls) //[1 2 3 4 5]

string:

//字符串排序,现比较高位,相同的再比较低位
ls := sort.StringSlice{
"",
"",
"",
"",
"",
}
fmt.Println(ls) //[100 42 41 3 2]
sort.Strings(ls)
fmt.Println(ls) //[100 2 3 41 42] //字符串排序,现比较高位,相同的再比较低位
ls := sort.StringSlice{
"d",
"ac",
"c",
"ab",
"e",
}
fmt.Println(ls) //[d ac c ab e]
sort.Strings(ls)
fmt.Println(ls) //[ab ac c d e] //汉字排序,依次比较byte大小
ls := sort.StringSlice{
"啊",
"博",
"次",
"得",
"饿",
"周",
}
fmt.Println(ls) //[啊 博 次 得 饿 周]
sort.Strings(ls)
fmt.Println(ls) //[博 周 啊 得 次 饿] for _, v := range ls{
fmt.Println(v, []byte(v))
} //博 [229 141 154]
//周 [229 145 168]
//啊 [229 149 138]
//得 [229 190 151]
//次 [230 172 161]
//饿 [233 165 191]

复杂结构:

1. [][]int :

type testSlice [][]int

func (l testSlice) Len() int            { return len(l) }
func (l testSlice) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l testSlice) Less(i, j int) bool { return l[i][] < l[j][] } func main() {
ls := testSlice{
{,},
{,},
{,},
} fmt.Println(ls) //[[1 4] [9 3] [7 5]]
sort.Sort(ls)
fmt.Println(ls) //[[9 3] [1 4] [7 5]]
}

2. []map[string]int     [{"k":0},{"k1":1},{"k2":2] :

type testSlice []map[string]float64

func (l testSlice) Len() int            { return len(l) }
func (l testSlice) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l testSlice) Less(i, j int) bool { return l[i]["a"] < l[j]["a"] } //按照"a"对应的值排序 func main() {
ls := testSlice{
{"a":, "b":},
{"a":, "b":},
{"a":, "b":},
} fmt.Println(ls) //[map[a:4 b:12] map[a:3 b:11] map[a:5 b:10]]
sort.Sort(ls)
fmt.Println(ls) //[map[a:3 b:11] map[a:4 b:12] map[a:5 b:10]]
}

3. []struct :

type People struct {
Name string `json:"name"`
Age int `json:"age"`
} type testSlice []People func (l testSlice) Len() int { return len(l) }
func (l testSlice) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l testSlice) Less(i, j int) bool { return l[i].Age < l[j].Age } func main() {
ls := testSlice{
{Name:"n1", Age:},
{Name:"n2", Age:},
{Name:"n3", Age:},
} fmt.Println(ls) //[{n1 12} {n2 11} {n3 10}]
sort.Sort(ls)
fmt.Println(ls) //[{n3 10} {n2 11} {n1 12}]
}

4. 复杂的时候,按float64类型排序:

type People struct {
Name string `json:"name"`
Age float64 `json:"age"`
}
func isNaN(f float64) bool {
return f != f
}
type testSlice []People func (l testSlice) Len() int { return len(l) }
func (l testSlice) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l testSlice) Less(i, j int) bool { return l[i].Age < l[j].Age || isNaN(l[i].Age) && !isNaN(l[j].Age)} func main() {
ls := testSlice{
{Name:"n1", Age:12.12},
{Name:"n2", Age:11.11},
{Name:"n3", Age:10.10},
} fmt.Println(ls) //[{n1 12.12} {n2 11.11} {n3 10.1}]
sort.Sort(ls)
fmt.Println(ls) //[{n3 10.1} {n2 11.11} {n1 12.12}]
}