第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定

Golang 學(xué)習(xí)筆記——排序

標(biāo)簽:
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)
點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報(bào)

0/150
提交
取消