1. 程式人生 > 其它 >Go sort包

Go sort包

sort包簡介

官方文件
Golang的sort包用來排序,二分查詢等操作。本文主要介紹sort包裡常用的函式,通過例項程式碼來快速學會使用sort包

sort包內建函式

sort.Ints(x []int)

	ints := []int{1, 4, 3, 2}
	fmt.Printf("%v\n", ints) 
	sort.Ints(ints) //預設升序
	fmt.Printf("%v\n", ints) //[1 2 3 4] 
	sort.Sort(sort.Reverse(sort.IntSlice(ints))) //降序排序 
	fmt.Printf("%v\n", ints) //[4 3 2 1]

sort.Strings(x []string) sort.Float64s(x []float64)

  • 使用方法同上,都是對內建int string float6型別的便捷排序

sort.Slice(x any, less func(i, j int) bool)

  • 傳入物件是切片,要自己實現回撥函式
	slices := []int{1, 1, 4, 5, 1, 4}
	sort.Slice(slices, func(i, j int) bool {
		return slices[i] < slices[j]
	})
	fmt.Printf("%v\n", slices)//[1 1 1 4 4 5]
  • 同時也可以對結構體自定義排序規則
	type stu struct {
		name string
		age  int
	}

	stus := []stu{{"h", 20}, {"a", 23}, {"h", 21}}
	sort.Slice(stus, func(i, j int) bool {
		if stus[i].name == stus[j].name {
			return stus[i].age > stus[j].age // 年齡逆序
		}
		return stus[i].name < stus[j].name // 名字正序
	})
	fmt.Printf("%v\n", stus) //[{a 23} {h 21} {h 20}]

sort.Sort(data Interface)

  • 自定義排序,需要實現 Len() Less() Swap() 三個方法
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)
}
  • 使用程式碼
type stu struct {
	name string
	age  int
}
type student []stu

func (s student) Len() int {
	return len(s)
}
func (s student) Less(i, j int) bool {
	if s[i].name == s[j].name {
		return s[i].age > s[j].age // 年齡逆序
	}
	return s[i].name < s[j].name // 名字正序
}
func (s student) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func main() {
	stus1 := student{{"h", 20}, {"a", 23}, {"h", 21}}
	sort.Sort(stus1)
	fmt.Printf("%v\n", stus1) //[{a 23} {h 21} {h 20}] 使用效果等同於sort.Slice
}
  • 使用效果等同於sort.Slice後者程式碼量較少

sort.SearchInts(a []int, x int) int

  • 該函式是用來二分查詢的, 預設是在左邊插入
	arr := []int{1, 2, 3, 4, 5, 6, 7}
	idx := sort.SearchInts(arr, 4)
	fmt.Printf("%v\n", idx) // 3

sort.SearchFloat64s(a []float64, x float64) int sort.SearchStrings(a []string, x string) int

  • 這兩函式功能同上

sort.Search(n int, f func(int) bool) int

  • 自定義的二分查詢,回撥函式搖自己實現查詢條件
	arr := []int{1, 2, 3, 4, 5, 6, 7}
	idx := sort.Search(len(arr), func(i int) bool {
		return arr[i] > 4
	})
	fmt.Printf("%v\n", idx) //4
  • 相比SearchInts,通過自定義條件便實現了相等情況下在右邊插入,前者預設是在左邊
  • 更高階一點的用法
	mysring := []string{"abcd", "bcde", "bfag", "cddd"}
	idx := sort.Search(len(mysring), func(i int) bool {
		// 查詢頭兩位字母不是b的,,返回找到的第一個
		return mysring[i][0] != 'b' && mysring[i][1] != 'b'
	})
	fmt.Printf("%v\n", mysring[idx]) // cddd
	mysring := []string{"abcd", "bcde", "bfag", "cddd"}
	idx := sort.Search(len(mysring), func(i int) bool {
		//查詢第一個字母不是b的
		return mysring[i][0] <= byte('b')
	})
	fmt.Printf("%v\n", mysring[idx]) // abcd