JavaScript Program to Find median in row wise sorted matrix


We will be describing the process of finding the median in a row-wise sorted matrix using JavaScript. First, we will traverse the matrix to gather all the elements into a single array. Then, we will sort the array to find the middle value, which will be our median. In case of an even number of elements, the median will be the average of the two middle values.

Approach

Given a row-wise sorted matrix, the median can be found by the following approach −

  • Combine all rows into a single sorted array.

  • Find the middle element(s) of the combined array, which will be the median.

  • If the number of elements in the combined array is odd, return the middle element as the median.

  • If the number of elements in the combined array is even, return the average of the two middle elements as the median.

  • The time complexity for this approach is O(m * n log (m * n)), where m is the number of rows and n is the number of columns in the matrix.

  • The space complexity is O(m * n), as the entire matrix needs to be combined into a single array.

Example

Here is a complete working example of a JavaScript function to find the median in a row-wise sorted matrix −

function findMedian(matrix) {
   
   // Get the total number of elements in the matrix
   const totalElements = matrix.length * matrix[0].length;
   
   // Calculate the middle index of the matrix
   const middleIndex = Math.floor(totalElements / 2);
   
   // Initialize start and end variables to keep track of the search space
   let start = matrix[0][0];
   let end = matrix[matrix.length - 1][matrix[0].length - 1];
    
   while (start <= end) {
   
      // Calculate the mid point
      let mid = Math.floor((start + end) / 2);
      
      // Initialize a counter to keep track of the number of elements less than or equal to the mid value
      let count = 0;
      
      // Initialize a variable to store the row index of the last element less than or equal to the mid value
      let rowIndex = -1;
          
      // Loop through each row in the matrix
      for (let i = 0; i < matrix.length; i++) {
      
         // Use binary search to find the first element greater than the mid value in the current row
         let columnIndex = binarySearch(matrix[i], mid);
         
         // If the current row has no element greater than the mid value, increment the count by the length of the row
         if (columnIndex === -1) {
            count += matrix[i].length;
            rowIndex = i;
         } else {
         
            // Otherwise, increment the count by the column index of the first element greater than the mid value
            count += columnIndex;
            break;
         }
      }
         
      // Check if the count of elements less than or equal to the mid value is greater than or equal to the middle index
      if (count >= middleIndex) {
         end = mid - 1;
      } else {
         start = mid + 1;
         rowIndex++;
      }
         
      // Check if we have reached the middle index
      if (count === middleIndex) {
         return matrix[rowIndex][middleIndex - count];
      }
   }
  
   return start;
}

// Helper function for binary search
function binarySearch(arr, target) {
   let start = 0;
   let end = arr.length - 1;
     
   while (start <= end) {
      let mid = Math.floor((start + end) / 2);
      if (arr[mid] === target) {
         return mid;
      } else if (arr[mid] < target) {
         start = mid + 1;
      } else {
         end = mid - 1;
      }
   }
     
   return start === 0 ? -1 : start - 1;
}
const arr = [
   [1, 2, 3], 
   [4, 5, 6], 
   [7, 8, 9]
];

console.log(findMedian(arr));

Explanation

  • The findMedian function takes in a matrix as an argument. It first calculates the total number of elements in the matrix and the middle index (the median) using totalElements and middleIndex respectively.

  • The start and end variables are initialized to the first and last elements of the matrix, respectively, as these are the minimum and maximum values in the matrix.

Updated on: 15-Mar-2023

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements