wx

关注公众号

sort


Golang 标准库 - sort

sort 包提供了对切片和用户定义集合的排序功能。Go 1.8+ 引入了便捷函数 Sort、Slice、SliceStable 等。

主要功能说明:

  1. 基本类型排序

    • Ints() 整数排序
    • Float64s() 浮点数排序
    • Strings() 字符串排序
    • SearchInts() 二分查找
  2. 自定义排序

    • Slice() 自定义比较函数排序
    • SliceStable() 稳定排序
    • Sort() 实现 Interface 接口
  3. 搜索

    • Search() 二分搜索
    • SearchInts() 在整数切片中搜索
    • SearchStrings() 在字符串切片中搜索
  4. 自定义类型

    • 实现 sort.Interface
    • Len()/Less()/Swap() 方法

// 自定义类型排序
type Person struct {
	Name string
	Age  int
}

type ByAge []Person

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

func main() {
	// 1. 基本类型排序
	fmt.Println("=== 基本类型排序 ===")
	
	nums := []int{5, 2, 6, 3, 1, 4}
	sort.Ints(nums)
	fmt.Println("Ints:", nums)

	floats := []float64{3.14, 2.71, 1.41, 1.73}
	sort.Float64s(floats)
	fmt.Println("Float64s:", floats)

	strs := []string{"banana", "apple", "cherry"}
	sort.Strings(strs)
	fmt.Println("Strings:", strs)

	// 2. 检查是否已排序
	fmt.Println("Ints are sorted:", sort.IntsAreSorted(nums))

	// 3. 自定义排序 - 使用 Slice
	fmt.Println("\n=== 自定义排序 ===")
	people := []Person{
		{"Alice", 30},
		{"Bob", 25},
		{"Charlie", 35},
	}
	
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})
	fmt.Println("按年龄排序:", people)

	// 4. 稳定排序
	fmt.Println("\n=== 稳定排序 ===")
	items := []Person{
		{"Alice", 30},
		{"Bob", 25},
		{"Charlie", 30},
	}
	sort.SliceStable(items, func(i, j int) bool {
		return items[i].Age < items[j].Age
	})
	fmt.Println("稳定排序结果:", items)

	// 5. 二分搜索
	fmt.Println("\n=== 二分搜索 ===")
	nums = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	
	// 查找存在的元素
	idx := sort.SearchInts(nums, 5)
	fmt.Printf("5 的位置: %d\n", idx)

	// 查找不存在的元素,返回应该插入的位置
	idx = sort.SearchInts(nums, 10)
	fmt.Printf("10 应该插入的位置: %d\n", idx)

	// 通用 Search
	idx = sort.Search(len(nums), func(i int) bool {
		return nums[i] >= 6
	})
	fmt.Printf("第一个 >=6 的位置: %d\n", idx)

	// 6. 使用 sort.Interface
	fmt.Println("\n=== 使用 sort.Interface ===")
	byAge := ByAge{
		{"David", 40},
		{"Eve", 20},
		{"Frank", 30},
	}
	sort.Sort(byAge)
	fmt.Println("按年龄排序:", byAge)
	
	// 反向排序
	sort.Sort(sort.Reverse(byAge))
	fmt.Println("反向排序:", byAge)
}
如有疑问关注公众号给我留言
wx

关注公众号

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo