![]() |
VOOZH | about |
Given a sorted matrix of size n*n. Calculate the mean and median of the matrix .
Examples:
Input : 1 2 3
4 5 6
7 8 9
Output :Mean: 5
Median: 5
Input : 1 1 1
2 2 2
4 4 4
Output :Mean: 2
Median: 2
Mean of matrix is =
(sum of all elements of matrix)/
(total elements of matrix)
Note that this definition doesn't require
matrix to be sorted and works for all
matrices.
Median of a sorted matrix is calculated as:
1. When n is odd
median is mat[n/2][n/2]
2. When n is even, median is average
of middle two elements.
Middle two elements can be found at indexes
a[(n-2)/2][n-1] and a[n/2][0]
If given matrix is unsorted, we can find its median by first sorting the matrix.
Implementation:
Mean : 8.5 Median : 8.5
Time complexity: O(N2) as using two for loops
Auxiliary Space: O(1)
METHOD 2:Using functions
APPROACH:
This Python program calculates the mean and median of a given matrix using functions. The program first defines two functions - mean() and median(), which take the matrix as an argument and return the calculated mean and median values, respectively. It then creates a 3x3 matrix and calls these functions to calculate the mean and median of the matrix. Finally, the program prints out the calculated mean and median values.
ALGORITHM:
Mean: 5.0 Median: 5
Time Complexity: The time complexity of this program is O(nlogn) for sorting the list, where n is the total number of elements in the matrix.
Space Complexity: The space complexity of this program is O(n) for storing the flattened list, where n is the total number of elements in the matrix.