Golang语言排序的几种方式

Stella981
• 阅读 537

1.Ints,float64s,strings

使用以如函数实现基本类型

  • sort.Ints

  • sort.Float64s

  • sort.Strings

    s := []int{4, 2, 3, 1}
    sort.Ints(s)
    fmt.Println(s) // [1 2 3 4]
    

2.结构体自定义排序

  • 使sort.Slice用函数,它使用提供了less(i int,j int)函数返回布尔值,对切片进行排序

  • 若要在保持相等元素的原始顺序的同时对切片进行排序,请使用sort.SliceStable函数

    family := []struct { Name string Age int}{ {"Alice", 23}, {"David", 2}, {"Eve", 2}, {"Bob", 25}, }// Sort by age, keeping original order or equal elements.sort.SliceStable(family, func(i, j int) bool { return family[i].Age < family[j].Age }) fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

3.结构体自定义排序2

  • 使用通用sort.Sortsort.Stable functions排序功能

  • 对要排序的集合要实现sort.Interface接口

    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 Person struct {
    Name string
    Age  int}// ByAge implements sort.Interface based on the Age field.type ByAge []Personfunc (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() {
    family := []Person{
        {"Alice", 23},
        {"Eve", 2},
        {"Bob", 25},
    }
    sort.Sort(ByAge(family))
    fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]}

4.map排序

map是键值对是一个无序集合。如果需要稳定的迭代顺序,则必须维护独立的数据结构比如:

m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}

keys := make([]string, 0, len(m))for k := range m {
    keys = append(keys, k)
}
sort.Strings(keys)for _, k := range keys {
    fmt.Println(k, m[k])
}// Output:// Alice 2// Bob 3// Cecil 1

最后

最近在写基于Golang的工具和框架,还请多多Star.
YoyoGo是一个用 Go 编写的简单,轻便,快速的 微服务框架,目前已实现了Web框架的能力,但是底层设计已支持多种服务架构。

Github

https://github.com/yoyofx/yoyogo
https://github.com/yoyofxteam

本文分享自微信公众号 - 晋级CTO(up_cto)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Andy20 Andy20
3年前
go语言之进阶篇字符串操作常用函数介绍
下面这些函数来自于strings包,这里介绍一些我平常经常用到的函数,更详细的请参考官方的文档。一、字符串操作常用函数介绍1、ContainsfuncContains(s,substrstring)bool功能:字符串s中是否包含substr,返回bool值示例:fmt.Println(strings.Contains(
Souleigh ✨ Souleigh ✨
2年前
前端性能优化 - 雅虎军规
无论是在工作中,还是在面试中,web前端性能的优化都是很重要的,那么我们进行优化需要从哪些方面入手呢?可以遵循雅虎的前端优化35条军规,这样对于优化有一个比较清晰的方向.35条军规1.尽量减少HTTP请求个数——须权衡2.使用CDN(内容分发网络)3.为文件头指定Expires或CacheControl,使内容具有缓存性。4.避免空的
Stella981 Stella981
2年前
Redis 为什么这么快? Redis 的有序集合 zset 的底层实现原理是什么? —— 跳跃表 skiplist
Redis有序集合zset的底层实现——跳跃表skiplistRedis简介Redis是一个开源的内存中的数据结构存储系统,它可以用作:数据库、缓存和消息中间件。它支持多种类型的数据结构,如字符串(Strings),散列(Hash),列表(List),集合(S
Stella981 Stella981
2年前
JS 对象数组Array 根据对象object key的值排序sort,很风骚哦
有个js对象数组varary\{id:1,name:"b"},{id:2,name:"b"}\需求是根据name或者id的值来排序,这里有个风骚的函数函数定义:function keysrt(key,desc) {  return function(a,b){    return desc ? ~~(ak
Stella981 Stella981
2年前
Python time模块 返回格式化时间
常用命令  strftimetime.strftime("%Y%m%d%H:%M:%S",formattime)第二个参数为可选参数,不填第二个参数则返回格式化后的当前时间日期201812112:00:00time.strftime('%H:%M:%S')返回当前时间的时分秒time.strftim
Stella981 Stella981
2年前
SpringBoot开发案例之整合Dubbo提供者(二)
!00.jpg(https://blog.52itstyle.com/usr/uploads/2017/07/1329278006.jpg)大家有没有注意到,上一篇中提供者,暴露接口的方式?混搭。springboot本身接口实现使用了注解的方式,而Dubbo暴露接口使用的是配置文件的实现方式,即如下:代码importorg.s
Easter79 Easter79
2年前
SpringBoot开发案例之整合Dubbo提供者(二)
!00.jpg(https://blog.52itstyle.com/usr/uploads/2017/07/1329278006.jpg)大家有没有注意到,上一篇中提供者,暴露接口的方式?混搭。springboot本身接口实现使用了注解的方式,而Dubbo暴露接口使用的是配置文件的实现方式,即如下:代码importorg.s
双寿 双寿
3个月前
慕课甄选-2024年Flutter零基础极速入门到进阶实战[16章]
参考资料地址1:https://pan.baidu.com/s/1j35W30a7JQAGTV2rYgxRNA提取码:5o3h参考资料地址2:https://pan.baidu.com/s/1Iwj10AL7jdum19WQz1jdA提取码:0n8xFlu