Sorting in Golang with sort Package


The standard library of Golang provides a package that we can use if we want to sort arrays, slices, or even custom types. In this article, we will discover three main functions that we can use if we want to sort a slice in Golang. We will also see how we can create a custom sort function and custom comparator.

Let's first check how we can sort a slice of integer, float64 and string values.

Example

Consider the code shown below.

package main
import (
   "fmt"
   "sort"
)
func main() {
   integerSlice := []int{3, 2, 14, 9, 11}
   sort.Ints(integerSlice)
   fmt.Println("After sorting", integerSlice)

   floatSlice := []float64{2.32, 9.87, 1.98, 0.88}
   sort.Float64s(floatSlice)
   fmt.Println("After sorting", floatSlice)

   stringSlice := []string{"mukul", "shreya", "naman"}
   sort.Strings(stringSlice)
   fmt.Println(stringSlice)
}

In the above code, we have used the following three functions of the sort package

  • sort.Ints

  • sort.Float64s

  • sort.Strings

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

After sorting [2 3 9 11 14]
After sorting [0.88 1.98 2.32 9.87]
[mukul naman shreya]

Sorting with a custom comparator

Example

We can define a custom comparator also in case we want to sort a struct in Go. Consider the code shown below.

package main
import (
   "fmt"
   "sort"
)
type Person struct {
   name string
   age int
}
func main() {
   people := []Person{{"Mukul", 24}, {"Deepak", 26}, {"Mayank", 24}}
   fmt.Println("Before sorting", people)

   // sorting on the basis of age
   sort.Slice(people, func(i, j int) bool {
      return people[i].age < people[j].age
   })
   fmt.Println("After sorting1", people)

   // sorting on the basis of name
   sort.Slice(people, func(i, j int) bool {
      return people[i].name < people[j].name
   })
   fmt.Println("After sorting2", people)
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Before sorting [{Mukul 24} {Deepak 26} {Mayank 24}]
After sorting1 [{Mukul 24} {Mayank 24} {Deepak 26}]
After sorting2 [{Deepak 26} {Mayank 24} {Mukul 24}]

Updated on: 22-Feb-2022

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements