Using sort package in Go

Posted drvongoosewing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

 

 

 

 

 

以上是关于Using sort package in Go的主要内容,如果未能解决你的问题,请参考以下文章

小问题为啥乱搞就不行,golang没安装在系统目录下,导致go get出现"package bytes: directory "/home/ahfu/go/src/bytes&(代

An introduction to using and visualizing channels in Go

[NPM] Test npm packages locally in another project using npm link

Most basic operations in Go are not synchronized. In other words, they are not concurrency-safe.(示例代

Sort a linked list in O(n log n) time using constant space complexity.

解决pip install package时Fatal error in launcher: Unable to create process using '"e:python36(