find the median of a list of numbers in go

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.go
import (
    "sort"
    "math"
)

func median(numbers []float64) float64 {
    sort.Float64s(numbers) // sort in ascending order

    n := len(numbers)
    mid := n / 2

    if n % 2 == 0 {
        // even number of elements, return average of two middle numbers
        return (numbers[mid-1] + numbers[mid]) / 2.0
    } else {
        // odd number of elements, return middle number
        return numbers[mid]
    }
}
421 chars
20 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.

related categories

gistlibby LogSnag