How to sort a slice in Golang?


In Go programming language, a slice is a dynamic array that can hold a sequence of elements of the same type. Slices can be sorted using the built-in sort package. In this article, we will discuss how to sort a slice in Golang.

Sorting a slice in Go is simple, and there are several ways to accomplish it. The most common way is to use the sort.Slice() function, which sorts a slice using a provided comparison function. Here's how it works −

Example

package main

import (
   "fmt"
   "sort"
)

func main() {
   s := []int{5, 2, 6, 3, 1, 4}
   fmt.Println("Original slice:", s)

   sort.Slice(s, func(i, j int) bool {
      return s[i] < s[j]
   })
   fmt.Println("Sorted slice:", s)
}

Output

Original slice: [5 2 6 3 1 4]
Sorted slice: [1 2 3 4 5 6]

In the above example, we create a slice of integers with the values 5, 2, 6, 3, 1, and 4. We then use the sort.Slice() function to sort the slice in ascending order. The function takes two arguments: the slice to sort and a comparison function that determines the order of the elements. In this case, the comparison function compares two elements in the slice and returns true if the first element is less than the second element.

The sort.Slice() function can also sort a slice in descending order by reversing the comparison logic −

Example

package main

import (
   "fmt"
   "sort"
)

func main() {
   s := []int{5, 2, 6, 3, 1, 4}
   fmt.Println("Original slice:", s)

   sort.Slice(s, func(i, j int) bool {
      return s[i] > s[j]
   })

   fmt.Println("Sorted slice:", s)
}

Output

Original slice: [5 2 6 3 1 4]
Sorted slice: [6 5 4 3 2 1]

In the above example, we use the same slice of integers as before but sort it in descending order by reversing the comparison logic.

In addition to sort.Slice(), the sort package also provides other sorting functions, such as sort.Ints() and sort.Strings(), that are optimized for sorting specific types of slices.

Example

package main

import (
   "fmt"
   "sort"
)

func main() {
   s := []int{5, 2, 6, 3, 1, 4}
   fmt.Println("Original slice:", s)

   sort.Ints(s)

   fmt.Println("Sorted slice:", s)
}

Output

Original slice: [5 2 6 3 1 4]
Sorted slice: [1 2 3 4 5 6]

In the above example, we use the sort.Ints() function to sort a slice of integers in ascending order.

Conclusion

Sorting a slice in Golang is easy and can be accomplished using the built-in sort package. By using the appropriate sorting function or comparison function, you can sort a slice in ascending or descending order. Understanding how to sort slices is essential for writing efficient and effective Go code.

Updated on: 25-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements