使用golang的sort包进行排序

紫葡萄 · · 1592 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

这是在掘金的第一篇文章,之前一直在某书发文章,进来感觉某书越来越不好了,想把文章 都搬到掘金来。

介绍

golang和java等语言一样,系统自带了一个排序方法,可以快速实现排序。废话不多说,先上栗子,再解释。

package main

import (
	"fmt"
	"math/rand"
	"sort"
	"strconv"
)

func main() {
	oneArr := make([]*One, 10)
	for i := 0; i < 10; i++ {
		oneArr[i] = &One{
			Name: "name" + strconv.FormatInt(int64(i), 10),
			Num:  rand.Intn(1000),
		}
	}

	for _, v := range oneArr {
		fmt.Print(v, " ")
	}
	fmt.Println()
	sort.Sort(OneList(oneArr))
	for _, v := range oneArr {
		fmt.Print(v, " ")
	}
	fmt.Println()

}

type One struct {
	Num  int
	Name string
}

type OneList []*One

func (this OneList) Len() int {
	return len(this)
}
func (this OneList) Less(i, j int) bool {
	return this[i].Num < this[j].Num
}
func (this OneList) Swap(i, j int) {
	this[i], this[j] = this[j], this[i]
}
复制代码

运行结果

运行结果
实现从小到大排序

解释

使用type定义了一个 []*One 类型的OneList切片。OneLiit 实现Interface 这个接口 这个接口在sort 中定义,原型

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
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)
}
复制代码
  • Len() 函数 返回要排序的序列的长度
  • Less() 函数 返回排序需要的比较的规则,如果符合这个规则,就进行交换
  • Swap() 函数 进行排序的交换规则

OneList 重写这3个函数

新建一个切片oneArr,随机填充数据,然后调用sort包中的Sort()函数,进行排序。
Sort()函数需要传递一个Interface 类型的参数。 使用强制类型转换把 oneArr 转换为Interface类型。

sort包中 还有一个函数实现反向排序,sort.sort.Reverse()可以实现倒序排序

栗子 sort.Sort(sort.Reverse(OneList(oneArr))) 就能实现反向排序
结果:

实现从大到下排序

拓展

golang的sort包中为我们定义了一些常用的排序类型

  • type IntSlice []int int类型切片的排序
  • type Float64Slice []float64 float64 类型切片的排序
  • type StringSlice []string string 类型切片的排序

看一个应用栗子:

package main

import (
	"fmt"
	"math/rand"
	"sort"
)

func main() {
	one := make([]int, 10)
	for i := 0; i < 10; i++ {
		one[i] = int(rand.Int31n(1000))
	}
	fmt.Println(one)
	sort.Sort(sort.IntSlice(one))
	fmt.Println(one)

}
复制代码

运行结果:

好了,先介绍到这里。


有疑问加站长微信联系(非本文作者)

本文来自:掘金

感谢作者:紫葡萄

查看原文:使用golang的sort包进行排序

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1592 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传