Using sort package in Go

Introduction

There are many manipultions require us to sort a collection. Using sort package in Go is a good choice, we will avoid many hard codes by ourself. Not like Python, sort is a method built in each "list" we are using. In Go we will use some functional way to sort. There are some articles on internet decribe the usage too difficult, but actually Go gives us some quick access which we will talk about. One quick note before we begin, functions in package "sort" only accept Slice and interface data. Which makes we don‘t use Array.

In this article we will talk about:

1. How to sort an integer slice ([]int).

2. How to sort a float slice ([]float64).

3. How to sort a string slice ([]string).

4. How to reverse a sorted slice

How to sort an integer slice?

Go has build a function call sort.Ints() for us to sort an interger slice. We don‘t need any other additional code.

Notice we should use sort.Ints() standalone. Because this function has no return values and it will sort order inside original slice.

package main

import (
	"fmt"
	"sort"
)

func main() {
	list := []int{2, 5, 2, 9, 0}
	fmt.Println("Original list: ", list)
	sort.Ints(list)
	fmt.Println("Sorted list: ", list)
}

// output
Original list:  [2 5 2 9 0]
Sorted list:  [0 2 2 5 9]

We have another option to do the same thing. Using type sort.IntSlice as an type convert function. That is, sort.IntSlice().

With the power of sort.IntSlice, now we can acess many build in method attached to it, like .Sort().

And only after we convert slice into a sort.IntSlice, we can pass it‘s value to sort.Sort() function.

This function doesn‘t accept normal Slice, but only accepts interface data. By definition document it is: func Sort(data Interface).

sort.Stable() is another function works like sort.Sort(). For now, we don‘t need to distinguish them.

package main

import (
	"fmt"
	"sort"
)

func main() {
        // method .Sort()
	list:= []int{2, 5, 2, 9, 0}
	sort.IntSlice(list).Sort()
	fmt.Println(list)

        // function sort.Sort()
	list2 := []int{2, 5, 2, 9, 0}
	sort.Sort(sort.IntSlice(list2))
	fmt.Println(list2)

	// function sort.Stable()
	list3 := []int{2, 5, 2, 9, 0}
	sort.Stable(sort.IntSlice(list3))
	fmt.Println(list3)
}

// output
[0 2 2 5 9]
[0 2 2 5 9]
[0 2 2 5 9]

How to sort a float slice?

As in the case of interger, Go has build an function call sort.Float64s() to help us, without any other code.

Again we should use sort.Float64s() standalone. This function has no return values as well.

package main

import (
	"fmt"
	"sort"
)

func main() {
	list := []float64{2.2, 5.1, 2, 9, 0}
	fmt.Println("Original list : ", list)
	sort.Float64s(list)
	fmt.Println("Original list : ", list)
}

// output
Original list :  [2.2 5.1 2 9 0]
Original list :  [0 2 2.2 5.1 9]

Another option to do the same thing is using type convert function sort.Float64Slice().

With the power of sort.Float64Slice, we can use .Sort() methon and sort.Sort() function as well.

package main

import (
	"fmt"
	"sort"
)

func main() {
	// method .Sort()
	list := []float64{2.2, 5.1, 2, 9, 0}
	sort.Float64Slice(list).Sort()
	fmt.Println(list)

	// function sort.Sort()
	list2 := []float64{2.2, 5.1, 2, 9, 0}
	sort.Sort(sort.Float64Slice(list2))
	fmt.Println(list2)

	// function sort.Stable()
	list3 := []float64{2.2, 5.1, 2, 9, 0}
	sort.Stable(sort.Float64Slice(list3))
	fmt.Println(list3)
}

// output
[0 2 2.2 5.1 9]
[0 2 2.2 5.1 9]
[0 2 2.2 5.1 9]

  

How to sort a string slice?

Not surprisingly, firstly we have function sort.Strings() to sort a string slice.

package main

import (
	"fmt"
	"sort"
)

func main() {
	ss := []string{"b", "z", "a", "f", "g"}
	fmt.Println("Original string: ", ss)
	sort.Strings(ss)
	fmt.Println("Sorted string: ", ss)
}

// output
Original string:  [b z a f g]
Sorted string:  [a b f g z]

Secondly, we have sort.StringSlice and it‘s method.

package main

import (
	"fmt"
	"sort"
)

func main() {
	// method .Sort()
	ss := []string{"b", "z", "a", "f", "g"}
	sort.StringSlice(ss).Sort()
	fmt.Println(ss)

	// function sort.Sort()
	ss2 := []string{"b", "z", "a", "f", "g"}
	sort.Sort(sort.StringSlice(ss2))
	fmt.Println(ss2)

	// function sort.Stable()
	ss3 := []string{"b", "z", "a", "f", "g"}
	sort.Stable(sort.StringSlice(ss3))
	fmt.Println(ss3)
}

// output
[a b f g z]
[a b f g z]
[a b f g z]

How to reverse a sorted slice (or how to sort decreasing)?  

Algorithmically speaking, once we have an ascending sorted slice (by defualt), we don‘t specially need a decreasing slice.

Becuace we can use it from ending to beginning, which makes it decreasingly.

But in some case, having this decreasing slice will be convenience.

With the help of sort.IntSlice/ sort.FloatSlice/ sort.StringSlice, we can use function sort.Reverse(). This function will return an interface, once sort.Sort() accepts it, the result will be sorted decreasing.

The statement is not so straight forward, let‘s see what happends here.

package main

import (
	"fmt"
	"sort"
)

func main() {
	list := []int{2, 5, 2, 9, 0}
	sort.Sort(sort.Reverse(sort.IntSlice(list)))
	fmt.Println(list)
}

// output
[9 5 2 2 0]

We can see there are too many layers. Readability is somehow weaken but it‘s good to know.

Summary

1. Quick start: use sort.Ints() / sort.Float64s()/ sort.Strings().

2. sort.IntSlice/ sort.FloatSlice/ sort.StringSlice can expand our usage.

 

原文地址:https://www.cnblogs.com/drvongoosewing/p/12111606.html

时间: 2024-11-14 19:26:06

Using sort package in Go的相关文章

Java操作Redis之Jedis用法详解

Redis(Remote Dictionary Server,远程数据字典服务器)是一个开源的高性能内存数据库,常用作缓存缓存服务器使用,也已做消息队列使用.因其高性能.丰富的数据类型.可扩展等特性受开发者青睐,这里介绍在java中使用Jedis操作Redis的基本用法. 1. 字符串String. package com.zws.redis.examples; import java.util.concurrent.TimeUnit; import redis.clients.jedis.Je

Go语言(golang)开源项目大全

转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析器控制台用户界面加密数据处理数据结构数据库和存储开发工具分布式/网格计算文档编辑器Encodings and Character SetsGamesGISGo ImplementationsGraphics and AudioGUIs and Widget ToolkitsHardwareLangu

19-hadoop-fof好友推荐

好友推荐的案例, 需要两个job, 第一个进行好友关系度计算, 第二个job将计算的关系进行推荐 1, fof关系类 package com.wenbronk.friend; import org.apache.hadoop.io.Text; /** * 定义fof关系 * @author root * */ public class Fof extends Text{ public Fof() { super(); } /**' * 不论谁在前,返回一致的顺序 * @param a * @pa

18-hadoop-weather案例

weather案例, 简单分析每年的前三个月的最高温即可, 使用自定义的分组和排序 1, MyKey, 因为对温度进行分组, 排序, pardition操作, 所以默认的字典顺序不能满足需求 package com.wenbronk.weather; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.WritableCompara

GO语言的开源库

Indexes and search engines These sites provide indexes and search engines for Go packages: godoc.org gowalker gosearch Sourcegraph Contributing To edit this page you must be a contributor to the go-wiki project. To get contributor access, send mail t

JAVA基础学习day17--集合工具类-Collections

一.Collection简述 1.1.Collection与Collections的区别 Collections是集合的静态工具类 Collection:是集合的顶级接口 二.Sort 2.1.sort package com.pb.sort.demo1; import java.util.ArrayList; import java.util.Collections; /** * 对字符串进行自然排序 * */ public class SortDemo1 { public static vo

Play scala 7 一步一步QuickSort

1. 算法思想 如果一个待排序的数列,所有的数都已经在正确的位置上了,那么排序完毕. 先随便选一个数,把它放在正确的位置上.它左边是未排序的,右边也是未排序的. 此时,已经将在一个较长数列上排序的问题转化成了在两个较小数列上排序的问题. 参考:http://developer.51cto.com/art/201403/430986.htm 以数列 a = {6 , 1,  2, 7,  9,  3,  4,  5, 10 , 8} 为例 2. 为了将6放到正确的位置上(升序),我首先想到的是:从

java自定义类型 比较排序 Comparator接口

String service_time = "6:00:00,7:00:00,8:00:00,9:00:00,10:00:00,11:00:00,12:00:00,13:00:00,14:00:00,15:00:00,16:00:00,17:00:00,18:00:00,19:00:00,20:00:00,21:00:00,22:00:00 "; List<String> list = StringUtil.stringToList(service_time, "

[转]Go语言(golang)开源项目大全

内容目录 Astronomy 构建工具 缓存 云计算 命令行选项解析器 命令行工具 压缩 配置文件解析器 控制台用户界面 加密 数据处理 数据结构 数据库和存储 开发工具 分布式/网格计算 文档 编辑器 Encodings and Character Sets Games GIS Go Implementations Graphics and Audio GUIs and Widget Toolkits Hardware Language and Linguistics 日志 机器学习 Math