How to sort a slice of float64s in Golang?


In Go programming language, sorting a slice of float64 values is a common task in many applications. Fortunately, Go provides a built-in package sort that includes functions to sort slices of any type, including slices of float64 values. In this article, we will discuss how to sort a slice of float64s in Golang.

To sort a slice of float64 values in Go, we can use the sort.Float64s() 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 := []float64{5.4, 2.1, 6.7, 3.9, 1.2, 4.8}
   fmt.Println("Original slice:", s)

   sort.Float64s(s)

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

Output

Original slice: [5.4 2.1 6.7 3.9 1.2 4.8]
Sorted slice: [1.2 2.1 3.9 4.8 5.4 6.7]

In the above example, we create a slice of float64 values with the values 5.4, 2.1, 6.7, 3.9, 1.2, and 4.8. We then use the sort.Float64s() function to sort the slice in ascending order. The function takes a slice of float64 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 Float64Slice []float64

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

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

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

func main() {
   s := Float64Slice{5.4, 2.1, 6.7, 3.9, 1.2, 4.8}
   fmt.Println("Original slice:", s)

   sort.Sort(s)

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

Output

Original slice: [5.4 2.1 6.7 3.9 1.2 4.8]
Sorted slice: [6.7 5.4 4.8 3.9 2.1 1.2]

In the above example, we define a custom type Float64Slice that represents a slice of float64 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 float64 values using this custom type and sort the slice in descending order using the sort.Sort() function.

Conclusion

Sorting a slice of float64 values in Golang is easy and can be accomplished using the sort.Float64s() 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 float64 values is essential for writing efficient and effective Go code.

Updated on: 25-Apr-2023

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements