How to calculate the median of a matrix in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

func findMedianUnsortedMatrix(matrix [][]int) float64 {
    var elements []int

    // Flatten the matrix
    for _, row := range matrix {
        for _, val := range row {
            elements = append(elements, val)
        }
    }

    // Sort the elements
    sort.Ints(elements)

    // Calculate median
    n := len(elements)
    if n%2 == 1 {
        // Odd number of elements: return middle element
        return float64(elements[n/2])
    } else {
        // Even number of elements: return average of two middle elements
        return float64(elements[n/2-1]+elements[n/2]) / 2.0
    }
}

func main() {
    matrix := [][]int{
        {5, 8, 9, 10},
        {1, 4, 6, 13},
        {7, 3, 0, 18},
        {6, 8, 9, 20},
    }

    median := findMedianUnsortedMatrix(matrix)
    fmt.Printf("Median of the matrix is: %.1f\n", median)
}


/*
run:

Median of the matrix is: 7.5

*/

 



answered Oct 6, 2025 by avibootz
edited Oct 6, 2025 by avibootz

Related questions

...