To find the median of a list of numbers in Go, we can leverage the built-in sort
package and the math
package to calculate the median.
First, we need to sort the slice of numbers in ascending order using the sort
package. Once the slice is sorted, we can use the math
package to check if the length of the slice is odd or even. If it's odd, we simply return the middle element. If it's even, we return the average of the two middle elements.
Here's the code:
main.go421 chars20 lines
We define a function median
that takes in a slice of float64
values called numbers
. We first sort the slice using sort.Float64s
and then check if the length of the slice is even or odd. Finally, we return either the middle element or the average of the two middle elements.
Note: If the input slice is empty, this function will panic. You may want to include a check for this edge case.
gistlibby LogSnag