Open In App

How to Sort in Golang?

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting is a common operation in programming that organizes elements in a certain order. In Go, also known as Golang, the sort package provides functionalities for sorting arbitrary sequences. This article will guide you through the process of sorting in Golang.

What is Sorting?

Sorting is the process of arranging data in a particular format. The sorting algorithm specifies the way to arrange data in a particular order which can be in numerical or lexicographical order. The importance of sorting lies in the fact that data searching can be optimized to a very high level.

The Sort Package in Golang:

The sort package in Golang provides functions for sorting arbitrary sequences. It includes functions to sort slices of primitive types, to sort slices by providing a comparison function, and to sort data structures by implementing the Interface interface.

How to Sort In Golang? 

Here’s how you can sort a slice of integers in Golang:

Go
package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{5, 2, 6, 3, 1, 4}
sort.Ints(numbers)
fmt.Println(numbers) // Output: [1 2 3 4 5 6]
}

Output
[1 2 3 4 5 6]

In this code, we use the sort.Ints function to sort a slice of integers. The function sorts the slice in-place, meaning the original slice is modified.

Sorting Using a Custom Function

If you want to sort a slice using a custom function, you can use the sort.Slice function. 

Here’s an example:

Go
package main
import (
"fmt"
"sort"
)
type Employee struct {
Name string
Age int
}
func main() {
employees := []Employee{
{"John", 28},
{"Alice", 23},
{"Bob", 25},
}
sort.Slice(employees, func(i, j int) bool {
return employees[i].Age < employees[j].Age
})
fmt.Println(employees) // Output: [{Alice 23} {Bob 25} {John 28}]
}

Output
[{Alice 23} {Bob 25} {John 28}]

In this code, we define a Employee struct and create a slice of Employee. We then use the sort.Slice function to sort the slice by the Age field.


Next Article
Article Tags :

Similar Reads