How to Sort Float Reverse in Golang

You can sort a slice of floats in reverse order using the sort.Sort() along with the sort.Reverse() and sort.Float64Slice() function.

Steps to sort float reverse in Golang

  1. Convert the []float64 to sort.Float64Slice, which makes the slice an instance of the sort.Interface interface.
  2. Reverse the standard ascending order of the elements included in the sort.Float64Slice by using the sort.Reverse() function.
  3. Sort the reversed slice using the general sort.Sort() function.

Example

package main

import (
  "fmt"
  "sort"
)

func main() {
  float_slice := []float64{1.9, 2.1, 1.8, 4.6, 1.1}

  sort.Float64s(float_slice)
  fmt.Println(float_slice)

  sort.Sort(sort.Reverse(sort.Float64Slice(float_slice)))
  fmt.Println(float_slice)
}

Output

[1.1 1.8 1.9 2.1 4.6]
[4.6 2.1 1.9 1.8 1.1]

The custom type Float64Slice implements the sort.Interface interface, so it can be passed to the sort.Sort() function.

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

The sort.Float64s() function sorts the float64 slice in place and does not return a value. Then it prints the sorted slice.

Then, we sort the float_slice in reverse order using the sort.Sort() function and passing the result of the sort.Reverse(sort.Float64Slice(float_slice)) as the argument.

The sort.Reverse() function returns a new sort.Interface that will sort the elements in reverse order.

The sort.Float64Slice(float_slice) function is a wrapper around the float_slice of the float64 data type that implements the sort.Interface.

Finally, it prints the sorted slice in reverse order using the fmt.Println() function.

You can see from the output that we successfully sort the float values in reverse.

Conclusion

Use the combination of sort.Sort(), sort.Reverse(), and sort.Float64Slice() functions to sort a float in reverse order in Golang.

Further reading

How to Sort Int Reverse in Golang

How to sort a slice of strings in reverse

Leave a Comment