Given a row-wise sorted matrix having N number of rows and M number of columns. Your task is to find the median of the given matrix.
Note :
Assume that the size of the matrix N*M is always odd.
Input Format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test case contains two space separated integers N & M, the number of rows and columns respectively.
The next N lines of each test case contains M single space separated integers each, representing the elements of the matrix.
Output Format :
For each test case, print an integer denoting the median of the matrix.
The output of each test case is printed in a separate line.
Note :
You do not need to print anything, it has already taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N,M <= 10^4
-10^8 <= matrix[i][j] <= 10^8
Where 'matrix[i][j]' is the value of the element at 'jth' column of 'ith' row of the matrix.
Time Limit: 1 sec
1
3 3
1 3 5
2 6 9
3 6 9
5
On sorting the input matrix
1 2 3 3 5 6 6 9 9
The median of the above sorted array is its middle value and that is 5.
2
1 1
5
1 3
1 4 6
5
4
Sort the above matrix and make a 1D array.
The simplest way to find the median of the input matrix is to convert it into a 1D sorted array. Take an array of size N*M and push all the elements of the input matrix in the array. Sort the array and return the middle value, that is the median.
Algorithm:
O((N*M)*(log(N*M))), where N & M are the number of rows and columns of the input matrix respectively.
All the elements of the input matrix are pushed in an array taking O(N*M) time. The algorithm uses an inbuilt sorting algorithm to sort the array of size R*C. So, for sorting time complexity will be O((N*M)*(log(N*M))). So, the final time complexity of the algorithm is O(N*M) + O(N*M*(log(N*M))) = O(N*M*(log(N*M))).
O(N*M), where N & M are the number of rows and columns of the input matrix respectively.
An array of size N*M is required to store the elements of the input matrix.