How to sort a slice of ints in Golang?


Sorting a slice of int values is a common task in many applications, and Go provides a built-in package sort that includes functions to sort slices of any type, including slices of int values. In this article, we will discuss how to sort a slice of int values in Golang.

To sort a slice of int values in Go, we can use the sort.Ints() function provided by the sort package. Here's an example of how to use this function −

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 create a slice of int values with the values 5, 2, 6, 3, 1, and 4. We then use the sort.Ints() function to sort the slice in ascending order. The function takes a slice of int values as its argument and sorts the slice in-place.

If we want to sort the slice in descending order, we can use the sort.Sort() function and a custom implementation of the sort.Interface interface. Here's an example of how to do this −

Example

package main

import (
   "fmt"
   "sort"
)

type IntSlice []int

func (s IntSlice) Len() int {
   return len(s)
}

func (s IntSlice) Swap(i, j int) {
   s[i], s[j] = s[j], s[i]
}

func (s IntSlice) Less(i, j int) bool {
   return s[i] > s[j]
}

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

   sort.Sort(s)

   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 define a custom type IntSlice that represents a slice of int values. We then implement the sort.Interface interface for this type by defining the Len(), Swap(), and Less() methods. Finally, we create a slice of int values using this custom type and sort the slice in descending order using the sort.Sort() function.

Conclusion

Sorting a slice of int values in Golang is easy and can be accomplished using the sort.Ints() function provided by the sort package. If we want to sort the slice in descending order, we can define a custom implementation of the sort.Interface interface and use the sort.Sort() function. Understanding how to sort slices of int values is essential for writing efficient and effective Go code.

Updated on: 25-Apr-2023

725 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements