我是靠谱客的博主 危机铃铛,这篇文章主要介绍Golang 高效排序数据详情,现在分享给大家,希望可以做个参考。

1.介绍

Golang 语言项目开发中,经常会遇到数据排序问题。Golang 语言标准库 sort 包,为我们提供了数据排序的功能,我们可以直接使用 sort.Sort() 函数进行数据排序,sort.Sort() 函数底层实现是以快排为主,并根据目标数据的具体情况选择不同的排序算法。本文我们介绍 sort 包排序数据的使用方法。

2.切片排序

Golang 语言标准库 sort 包中,sort.Sort() 函数用于数据排序,该函数需要一个 interface 类型的入参 sort.Interface,它包含三个方法,分别是 Len()Less() Swap() 。也就是说,如果我们需要使用 sort 包的 Sort 函数进行数据排序,首先入参的数据需要实现这三个方法,或者理解为任意元素类型的切片实现了这三个方法,都可以使用 sort.Sort() 函数排序数据。

sort 包代码:

复制代码
1
2
3
4
5
6
7
type Interface interface { Len() int // 集合中元素的数量 Less(i, j int) bool // 描述元素的顺序 Swap(i, j int) // 交换索引为 i 和 j 的元素 } func Sort(data Interface)

需要注意的是 sort.Sort() 函数不能保证数据排序是稳定的,如果需要保证数据排序稳定,可以使用 sort.Stable() 函数,“稳定”的含义是原始数据中 a 和 b 的值相等,排序前 a 排在 b 的前面,排序后 a 仍排在 b 的前面。

为了方便读者朋友们理解,我们使用 int 类型的切片作为示例,介绍 sort.Sort() 函数的使用方法,我们定义一个类型 type IntSlice []int,并且给类型 IntSlice 实现 sort.Interface 接口类型定义的三个方法,然后使用 sort.Sort() 函数排序数据。

示例代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 () { intSlice := IntSlice([]int{1, 3, 5, 7, 9}) fmt.Println(intSlice) // 排序前 sort.Sort(intSlice) fmt.Println(intSlice) // 排序后 }

输出结构:

[9 7 5 3 1]
 
[1 3 5 7 9]

读到这里,我相信聪明的读者朋友们已经了解了 sort.Sort() 的使用方式,同时也会产生一个疑问,难道每次使用 sort.Sort() 排序数据,都需要这么麻烦吗?我还不如自己写个遍历排序数据。

是的,当然不用这么麻烦,sort 包已经帮我们封装好了常用函数,我们直接使用就可以了。所以,上面的示例代码可以使用 sort.Ints() 函数排序数据。

示例代码:

复制代码
1
2
3
4
5
6
func main () { intSlice := IntSlice([]int{9, 7, 5, 3, 1}) fmt.Println(intSlice) // 排序前 sort.Ints(intSlice) fmt.Println(intSlice) // 使用 sort.Ints() 排序数据 }

除了 sort.Ints() ,还有 sort.Float64s()sort.Strings()等。

3.自定义集合排序

Golang 语言项目开发中,我们经常会使用结构体,如果我们需要排序结构体类型的切片,应该怎么操作呢?

我们可以按照 Part 01 介绍的方式,实现那三个方法,然后调用 sort.Sort() 函数,当然,sort 包也为我们封装了排序结构体类型切片的函数 sort.Slice() ,但是,参数除了需要排序的数据之外,还需要提供一个 Less() 函数类型的参数。

示例代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
people := []struct { Name string Age int }{ {"Gopher", 7}, {"Alice", 55}, {"Vera", 24}, {"Bob", 75}, } sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name }) fmt.Println("By name:", people) sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) fmt.Println("By age:", people)

输出结果:

By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
 
By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]

4总结

本文我们介绍了怎么使用 Golang 语言标准库 sort 包排序数据,需要注意的是,除了本文使用的类型之外,其它任意类型只要实现 sort.Interface 的三个方法,都可以调用 sort.Sort() 函数排序数据。

到此这篇关于Golang 高效排序数据详情的文章就介绍到这了,更多相关Golang 高效排序数据内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是危机铃铛最近收集整理的关于Golang 高效排序数据详情的全部内容,更多相关Golang内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(147)

评论列表共有 0 条评论

立即
投稿
返回
顶部