We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.
Example:
Input: ->
1 3 5
2 6 9
3 6 9Output: -> 5
Explanation: The median is the middle element when all matrix elements are arranged in sorted order.
Simple Approach
- Store all elements in a 1D array of size r*c
- Sort the array
- Return the middle element
Complexity Analysis
- Time Complexity: O(r*c log(r*c))
- Space Complexity: O(r*c)
Efficient Approach (Binary Search)
An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be the median, there should be (r*c)/2 elements less than or equal to it. So, we count how many elements are less than or equal to mid.
Algorithm Steps
Step 1. Find range
- Minimum -> smallest among first elements of rows
- Maximum -> largest among last elements of rows
Step 2. Apply Binary Search
- Compute mid = (min + max) / 2
- Count elements ≤ mid in each row using upper_bound()
Step 3. Adjust search space
- If count < (r*c)/2 + 1 → median is greater → min = mid + 1
- Else -> median is smaller or equal → max = mid
Step 4. Repeat until min == max
- Repeat until min equals max, which gives the median.
Complexity Analysis
- Time Complexity: O(log(max - min) * r * log(c))
- Auxiliary Space: O(1)
import java.util.Arrays;
public class MedianInRowSorted
{
// function to find median in the matrix
static int binaryMedian(int m[][],int r, int c)
{
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i=0; i<r ; i++)
{
// Finding the minimum element
if(m[i][0] < min)
min = m[i][0];
// Finding the maximum element
if(m[i][c-1] > max)
max = m[i][c-1];
}
int desired = (r * c + 1) / 2;
while(min < max)
{
int mid = min + (max - min) / 2;
int place = 0;
int get = 0;
// Find count of elements smaller than mid
for(int i = 0; i < r; ++i)
{
get = Arrays.binarySearch(m[i],mid);
// If element is not found in the array the
// binarySearch() method returns
// (-(insertion_point) - 1). So once we know
// the insertion point we can find elements
// Smaller than the searched element by the
// following calculation
if(get < 0)
get = Math.abs(get) - 1;
// If element is found in the array it returns
// the index(any index in case of duplicate). So we go to last
// index of element which will give the number of
// elements smaller than the number including
// the searched element.
else
{
while(get < m[i].length && m[i][get] == mid)
get += 1;
}
place = place + get;
}
if (place < desired)
min = mid + 1;
else
max = mid;
}
return min;
}
// Driver Program to test above method.
public static void main(String[] args)
{
int r = 3, c = 3;
int m[][]= { {1,3,5}, {2,6,9}, {3,6,9} };
System.out.println("Median is " + binaryMedian(m, r, c));
}
}
// This code is contributed by Sumit Ghosh
Output
Median is 5
Explanation: Explanation: When all elements of the matrix are arranged in sorted order, the middle element represents the median. In this case, the sorted sequence gives 5 as the central value, so the median is 5.
Â