继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Golang 学习笔记——排序

兔头咖啡
关注TA
已关注
手记 6
粉丝 2
获赞 2

sort 包

sort 包是 Go 语言提供专门用于排序的包,任何实现了 sort.Interface 的类型,都可以使用 sort.Sort 进行排序。

type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	// Less reports whether the element with
	// index i should sort before the element with index j.
	Less(i, j int) bool
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

sort 包内置支持[]int、[]float64和[]string三种数据类型切片的排序。

import (
	"fmt"
	"sort"
)

func main() {
	var intSlice = []int{0, 33, 20, -23, 1, 40}

	sort.Ints(intSlice)
	fmt.Println(intSlice)

	var float64Slice = []float64{1.2, 4.2, -2.2, 8.8, 5.8}

	sort.Float64s(float64Slice)
	fmt.Println(float64Slice)

	var stringSlice = []string{"hello", "golang", "world", "bar", "foo"}

	sort.Strings(stringSlice)
	fmt.Println(stringSlice)
}

sort 包排序默认是升序,要想降序排序要利用 sort.Reverse 方法,它也接收一个实现 Interface 接口的参数。降序排序:

import (
	"fmt"
	"sort"
)

func main() {
	var intSlice = []int{0, 33, 20, -23, 1, 40}

	sort.Sort(sort.Reverse(sort.IntSlice(intSlice)))
	fmt.Println(intSlice)

	var float64Slice = []float64{1.2, 4.2, -2.2, 8.8, 5.8}

	sort.Sort(sort.Reverse(sort.Float64Slice(float64Slice)))
	fmt.Println(float64Slice)

	var stringSlice = []string{"hello", "golang", "world", "bar", "foo"}

	sort.Sort(sort.Reverse(sort.StringSlice(stringSlice)))
	fmt.Println(stringSlice)
}

自定义结构体排序

结构体排序要使用 sort.Sort(),结构体对应的slice要实现 sort.Interface 接口。

import (
	"fmt"
	"sort"
)

type User struct {
	Name string
	Age  int
}
type UserSlice []User

func (s UserSlice) Len() int {
	return len(s)
}
func (s UserSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s UserSlice) Less(i, j int) bool {
	return s[i].Age < s[j].Age
}

func main() {
	var userSlice = []User{
		{"bar1", 35},
		{"bar2", 44},
		{"bar3", 26},
		{"bar4", 18},
		{"bar5", 23},
	}
	sort.Sort(UserSlice(userSlice))
	fmt.Println(userSlice)
}

排序算法

sort 包内置了四种基本排序算法,分别是插入排序、堆排序、快速排序和归并排序,会根据实际数据自动选择高效的排序算法。

func insertionSort(data Interface, a, b int)

func heapSort(data Interface, a, b int)

func quickSort(data Interface, a, b, maxDepth int)

func symMerge(data Interface, a, m, b int)
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP