How to Sort Int Reverse in Golang

To sort an integer in reverse in Golang, use the “sort.Sort()” function with the data reversal function “sort.Reverse()” function.

The sort.Sort() is a generic sorting function from the standard library’s sort package.

The sort.Reverse() function allows you to sort a slice of elements in reverse order.

The sort.IntSlice() function that represents a slice of integers. The sort.IntSlice() function makes the slice an instance of the sort.Interface interface.

A golang slice of integers is a data structure that holds a sequence of integers and is represented by the []int type.

Example

package main

import (
  "fmt"
  "sort"
)

func main() {
  number_slice := []int{5, 2, 6, 3, 1, 4}

  sort.Ints(number_slice)
  fmt.Println(number_slice)

  sort.Sort(sort.Reverse(sort.IntSlice(number_slice)))
  fmt.Println(number_slice)
}

Output

[1 2 3 4 5 6]
[6 5 4 3 2 1]

In the above example, we first sort the number_slice in ascending order using the sort.Ints() function.

The sort.Ints() function sorts the slice in place and does not return a value. Then, we printed the sorted slice using the fmt.Println() function.

In the next line, we sort the number_slice in reverse order using the sort.Reverse(sort.IntSlice(number_slice)) as the argument.

The sort.Reverse() function returns a new sort.Interface that will sort the elements in reverse order and sort.IntSlice(number_slice) is a wrapper around the number_slice of integers that implements the sort.Interface.

We sorted the reversed slice using the general sort.Sort() function.

And finally, we get the output sorting integers in reverse.

Conclusion

Use the sort.Sort() function with the data reversal function sort.Reverse() function to sort an integer in reverse in Golang.

Further reading

How to sort a slice of strings in reverse

How to Sort Float Reverse in Golang