亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Golang 學習筆記——排序

標簽:
Go

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)
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
全棧工程師
手記
粉絲
2
獲贊與收藏
2

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消