go语言内置的sort包(对结构体排序)

下面是对Go语言内置`sort`包内容的详细概括:

1. 排序接口和方法

Interface 接口:
  Len() int: 返回集合的元素数量。
  Less(i, j int) bool: 报告索引`i`的元素是否应排序在索引`j`的元素之前。
  Swap(i, j int): 交换索引`i`和`j`的元素。

type Interface interface {
	// Len is the number of elements in the collection.
	Len() int


	Less(i, j int) bool

	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

- **排序函数**:
  - `Sort(data Interface)`: 对实现了`Interface`接口的集合进行排序。排序算法是快速排序,复杂度为`O(n*log(n))`。不保证稳定性。
  - `Stable(data Interface)`: 稳定排序算法,保留相等元素的原始顺序。复杂度为`O(n*log(n)*log(n))`。
  - `IsSorted(data Interface) bool`: 检查集合是否已排序。

 2. 反转排序

- **Reverse**:
  - `Reverse(data Interface) Interface`: 返回一个新的`Interface`实现,该实现按相反顺序排序。
  - `reverse` 结构体:嵌入`Interface`,并实现`Less`方法,使排序顺序相反。

3. 常用类型的排序

- **IntSlice** (`[]int`):
  - `Len() int`: 返回切片长度。
  - `Less(i, j int) bool`: 报告索引`i`的元素是否小于索引`j`的元素。
  - `Swap(i, j int)`: 交换索引`i`和`j`的元素。
  - `Sort()`: 对`IntSlice`进行排序。
  - `Search(x int) int`: 使用二分查找在`IntSlice`中搜索`x`的索引。

- **Float64Slice** (`[]float64`):
  - `Len() int`: 返回切片长度。
  - `Less(i, j int) bool`: 报告索引`i`的元素是否小于索引`j`的元素。对`NaN`值进行了特殊处理,`NaN`值排序在前。
  - `Swap(i, j int)`: 交换索引`i`和`j`的元素。
  - `Sort()`: 对`Float64Slice`进行排序。
  - `Search(x float64) int`: 使用二分查找在`Float64Slice`中搜索`x`的索引。

- **StringSlice** (`[]string`):
  - `Len() int`: 返回切片长度。
  - `Less(i, j int) bool`: 报告索引`i`的元素是否小于索引`j`的元素。
  - `Swap(i, j int)`: 交换索引`i`和`j`的元素。
  - `Sort()`: 对`StringSlice`进行排序。
  - `Search(x string) int`: 使用二分查找在`StringSlice`中搜索`x`的索引。

 4. 便利函数

- **Ints, Float64s, Strings**:
  - `Ints(x []int)`: 对`[]int`进行排序。
  - `Float64s(x []float64)`: 对`[]float64`进行排序。
  - `Strings(x []string)`: 对`[]string`进行排序。

- **IntsAreSorted, Float64sAreSorted, StringsAreSorted**:
  - `IntsAreSorted(x []int) bool`: 检查`[]int`是否已排序。
  - `Float64sAreSorted(x []float64) bool`: 检查`[]float64`是否已排序。
  - `StringsAreSorted(x []string) bool`: 检查`[]string`是否已排序。

 5. 二分查找

- **Search**:
  - `Search(n int, f func(int) bool) int`: 使用二分查找找到第一个满足`f(i)`为`true`的索引。

- **SearchInts, SearchFloat64s, SearchStrings**:
  - `SearchInts(a []int, x int) int`: 在排序的`[]int`中查找`x`的索引。
  - `SearchFloat64s(a []float64, x float64) int`: 在排序的`[]float64`中查找`x`的索引。
  - `SearchStrings(a []string, x string) int`: 在排序的`[]string`中查找`x`的索引。

 6. 切片排序

- **Slice, SliceStable, SliceIsSorted**:
  - `Slice(x any, less func(i, j int) bool)`: 对任意切片`x`使用比较函数`less`进行排序。使用反射确保`x`是一个切片。
  - `SliceStable(x any, less func(i, j int) bool)`: 对任意切片`x`使用比较函数`less`进行稳定排序。
  - `SliceIsSorted(x any, less func(i, j int) bool) bool`: 检查任意切片`x`是否已按照比较函数`less`排序。

通过这些接口和函数,`sort`包提供了对各种数据类型进行排序和查找的灵活工具,适用于各种排序需求。
下面是对结构体排序的示例:(根据Person年龄降序排序)

package main

import (
    "log"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    persons := []Person{
       {Name: "1", Age: 18},
       {Name: "2", Age: 20},
       {Name: "3", Age: 19},
       {Name: "4", Age: 30},
       {Name: "5", Age: 23},
    }

    sort.Slice(persons, func(i, j int) bool {
       return persons[i].Age > persons[j].Age
    })

    for _, value := range persons {
       log.Println(value.Name, value.Age)
    }

}


 

### Go语言 `sort.Sort` 使用教程 #### 接口定义 为了使用 `sort.Sort` 对数据进行排序,需实现 `sort.Interface` 接口。该接口含三个方法:`Len()`、`Less(i, j int) bool` 和 `Swap(i, j int)`[^1]。 #### 实现自定义类型并满足接口需求 下面展示如何创建一个实现了上述接口的新类型: ```go type IntSlice []int func (s IntSlice) Len() int { return len(s) } func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] } func (s IntSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } ``` 这段代码定义了一个名为 `IntSlice` 的新类型,并为其提供了必要的三种方法来满足 `sort.Interface` 要求。 #### 反转排序实例 对于希望按照降序排列的情况,可以利用 `sort.Reverse` 函数配合已有的升序逻辑完成操作: ```go numbers := []int{5, 2, 9, 1, 3} sort.Sort(sort.Reverse(IntSlice(numbers))) // 结果为 [9 5 3 2 1] ``` 此部分展示了通过组合 `sort.Sort` 和 `sort.Reverse` 来达到逆向排序的效果。 #### 完整示例程序 这里给出完整的可执行例子用于演示整个过程: ```go package main import ( "fmt" "sort" ) type IntSlice []int func (s IntSlice) Len() int { return len(s) } func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] } func (s IntSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func main() { numbers := []int{5, 2, 9, 1, 3} sort.Sort(IntSlice(numbers)) fmt.Println("Ascending order:", numbers) sort.Sort(sort.Reverse(IntSlice(numbers))) fmt.Println("Descending order:", numbers) } ``` 当运行以上代码时,将会看到先按升序再按降序打印出来的数组内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值