0
点赞
收藏
分享

微信扫一扫

golang标准库中的sort包

腾讯优测 2022-03-11 阅读 40
package main

import (
	"fmt"
	"sort"
)

func main() {
	// https://pkg.go.dev/sort#Ints
	s := []int{2, 4, 1, 3}
	// 排序正序
	sort.Ints(s)
	fmt.Printf("s: %v\n", s)
	// s: [1 2 3 4]

	f := []float64{1.1, 4.4, 5.5, 3.3, 2.2}
	sort.Float64s(f)
	fmt.Printf("f: %v\n", f)
	// f: [1.1 2.2 3.3 4.4 5.5]

	str := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
	sort.Strings(str)
	fmt.Println(str)
	// [Alpha Bravo Delta Go Gopher Grin]

	hz := sort.StringSlice{
		"我",
		"叫",
		"王",
		"帆",
		"啊",
	}
	fmt.Printf("hz: %v\n", hz)
	sort.Strings(hz)
	fmt.Printf("hz: %v\n", hz)
	for _, v := range hz {
		fmt.Println(v, []byte(v))
	}

}

在这里插入图片描述

less规则自己写!!!

map根据键排序 []map[string]float64

package main

import (
	"fmt"
	"sort"
)

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 {
	// 按照a对应的值排序
	return l[i]["a"] < l[j]["a"]
}

func main() {
	ls := testSlice{
		{"a": 4, "b": 12},
		{"a": 3, "b": 11},
		{"a": 5, "b": 10},
	}
	fmt.Printf("ls: %v\n", ls)
	sort.Sort(ls)
	fmt.Printf("ls: %v\n", ls)
}

在这里插入图片描述

复杂结构[][]int

package main

import (
	"fmt"
	"sort"
)

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 {
	// 按照a对应的值排序
	return l[i][1] < l[j][1]
}

func main() {
	ls := testSlice{
		{1, 4},
		{9, 3},
		{7, 5},
	}
	fmt.Printf("ls: %v\n", ls)
	sort.Sort(ls)
	fmt.Printf("ls: %v\n", ls)
}

在这里插入图片描述

负责结构体[]struct

package main

import (
	"fmt"
	"sort"
)

type People struct {
	Name string
	Age  int
}

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 {
	// 按照a对应的值排序
	return l[i].Age < l[j].Age
}

func main() {
	ls := testSlice{
		{Name: "n1", Age: 12},
		{Name: "n2", Age: 11},
		{Name: "n3", Age: 10},
	}
	fmt.Printf("ls: %v\n", ls)
	sort.Sort(ls)
	fmt.Printf("ls: %v\n", ls)
}

在这里插入图片描述

举报

相关推荐

0 条评论