Golang Sort Package

Sorting is an essential operation for many algorithms. Go provides sorting functions for many different data types. In this post, we will discuss about Golang sort package, which is used to sort elements in an array, list, slice, etc.

Importing Golang sort Package

To sort data types in Go we need to import the sort package.

import "sort"

The sorting function syntax

The sort functions in this package follow a specific pattern. For any data type data_type, the sort function of that data type is as follows.

sort.data_types(v []data_type)     // the sort function

An example would be for integers:

sort.Ints(i []int)  

To check if the slice is sorted we can use a function that also follows a similar pattern.

sort.data_typesAreSorted(v []data_type)       // check whether the data_type slice is sorted

The same function for a float64 would be as follows.

sort.Float64sAreSorted(v []Float64)        // check whether the float64 array is sorted 

Sorting functions in Go

All the sorting functions in Go returns a slice sorted in ascending order. Here is an example showing all sorts in action.

package main

import (
	"fmt"
	"sort"
)

func main() {
	i := []int{1, 2, 5, 1, 9, 5, 3, 7, 8, 23, 12, 67, 34, 45}        // unsorted array of ints
	
	f := []float64{2.3, 6.7, 3.2, 5.7, 9.2, 2.5, 4.9, 3.1}           // unsorted array of float64
	
	s := []string{"John", "Peter", "Luke", "Watson", "Turing"}        // unsorted array of strings
	
	
	sort.Ints(i)
	fmt.Println(i)            // [1 1 2 3 5 5 7 8 9 12 23 34 45 67]
	
	sort.Float64s(f)
	fmt.Println(f)            // [2.3 2.5 3.1 3.2 4.9 5.7 6.7 9.2]
	
	sort.Strings(s)
	fmt.Println(s)            // [John Luke Peter Turing Watson]
}

As you can see, each data type has a function that can be used for it. This is one of the benefits Go provides for sorting as remembering the functions are really easy.

Check whether a slice is sorted

To check whether a slice is sorted we can simply use a general function specific to that type. For strings, we can use the function as follows.

sort.StringsAreSorted(s []string)

Here is an example illustrating how to use those functions.

i := []int{1, 2, 3, 4}
fmt.Println(sort.IntsAreSorted(i))   // true

f := []float64{2.3, 4.5, 1.2}
fmt.Println(sort.Float64sAreSorted(f))    // false

s := []string{"Anaconda", "Jaguar", "Leopard", "Panda", "Bear"}
fmt.Println(sort.StringsAreSorted(s))     // false

In the code above sort.StringsAresorted() checks for lexicographical sorting.

Sorting a Collection of Custom Objects

A collection with custom objects can be sorted by using the sort function by implementing sort.Interface interface.

package main

import (
	"fmt"
	"sort"
)

// Create a custom type 
type Dog struct{
	Name string
	Size int
}

// define a collection of that type
type Dogs []Dog

// implement the functions from the sort.Interface
func (d Dogs) Len() int{ 
	return len(d) 
}

func (d Dogs) Less(i, j int) bool{ 
	return d[i].Size < d[j].Size 
}

func (d Dogs) Swap(i, j int){ 
	d[i], d[j] = d[j], d[i] 
}

func main() {

        // create a collection of data of that type
	dogs := []Dog{
		{"Terrier", 8},
		{"Pug", 10},
		{"Chihuahua", 6},
	}
	
        // convert to that collection while using the sort function
	sort.Sort(Dogs(dogs))
	
	fmt.Println(dogs)        // [{Chihuahua 6} {Terrier 8} {Pug 10}]
}

Using the reverse function

The reverse functions can be used for any data implementing the sort.Interface and can be used to sort it in reverse order.

For the basic types, we still need to implement the sort.Interface interface but there are these convenient functions that will make our lives a lot easier.

// for a data type this function is as follows
sort.data_typeSlice(v []data_type)

Here is the way to reverse the arrays of those data types.

package main

import (
	"fmt"
	"sort"
)

func main() {
	i := []int{1, 4, 2, 3, 7, 4, 2}
	
	sort.Sort(sort.Reverse(sort.IntSlice(i)))      // IntSlice function should be used
	
	fmt.Println(i) // [7 4 4 3 2 2 1]
}

In the code above, the function takes an integer slice and sorts it in reverse order.