Sorting in Golang

Sorting in Golang

Golang’s sort package implements sorting for builtins and user-defined types. There are 3 different ways to sort a slice in golang depending on the data stored in the slice.

Sort builtins types like int, float and string

package main

import (
	"fmt"
	"sort"
)

func main() {
	//sort slice containing strings
	strs := []string{"New York", "London", "Seattle"}
    sort.Strings(strs)
	fmt.Println("Strings:", strs)
	
	//sort slice containing ints
	ints := []int{17, 2, 14, 1, 5}
    sort.Ints(ints)
	fmt.Println("Ints: ", ints)
	
	//sort slice containing floats
	floats := []float64{23.93, 2.3, 2.5, 5.2}
	sort.Float64s(floats)
	fmt.Println("Floats: ", floats)
}

Output

Strings: [London New York Seattle]
Ints:  [1 2 5 14 17]
Floats:  [2.3 2.5 5.2 23.93]

Sort Custom Data Structures

Sometimes our collection holds custom data structures, we have to sort the collection depends on particular condition. Golang provides feature to sort custom data structures as well.
To sort custom data structures, type should implements interface below

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)
}

Program to sort custom data structures.

package main

import (
	"fmt"
	"sort"
)

type Emp struct {
	FirstName string
	LastName string
	Age int
}

type ByAge []Emp
func (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() {
	emps := []Emp{
        {"Rahul", "Anand", 29},
        {"C", "Anderson" , 20},
        {"Bob", "Anderson", 25},
	}
	
	sort.Sort(ByAge(emps))
	fmt.Println(emps)
}

Output

[{C Anderson 20} {Bob Anderson 25} {Rahul Anand 29}]

Sort using anonymous function (Custom Comparator)

Prior to Go 1.8, there is an easier way to sort a slice that does not require to define new types. You simply pass an anonymous function to the sort.Slice function

package main

import (
	"fmt"
	"sort"
)

func main() {
	emps := []struct {
		FirstName string
		LastName string
		Age int
	}{
        {"Rahul", "Anand", 29},
        {"C", "Anderson" , 20},
        {"Bob", "Anderson", 25},
	}
	
	sort.Slice(emps, func(i, j int) bool {
		return emps[i].Age < emps[j].Age
	})

	fmt.Println(emps)
}

Output

[{C Anderson 20} {Bob Anderson 25} {Rahul Anand 29}]

Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *