Javascript Program to Find median in row wise sorted matrix Last Updated : 12 Sep, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report 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.Examples: Input : 1 3 5 2 6 9 3 6 9Output : Median is 5If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9)Input: 1 3 4 2 5 6 7 8 9Output: Median is 5Simple Method: The simplest method to solve this problem is to store all the elements of the given matrix in an array of size r*c. Then we can either sort the array and find the median element in O(r*clog(r*c)) or we can use the approach discussed here to find the median in O(r*c). Auxiliary space required will be O(r*c) in both cases.An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be median there should be exactly (n/2) numbers which are less than this number. So, we try to find the count of numbers less than all the numbers. Below is the step by step algorithm for this approach: Algorithm: First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than our mid. And accordingly change the min or max.For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number.Below is the implementation of the above approach: JavaScript // JavaScript program to find median // of a matrix sorted row wise // Function to find median // in the matrix function binaryMedian(m, r, c) { let max = -1000000000; let min = 1000000000; for (let 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]; } let desired = parseInt((r * c + 1) / 2); while (min < max) { let mid = min + parseInt((max - min) / 2); let place = 0; let get = 0; // Find count of elements // smaller than mid for (let i = 0; i < r; ++i) { let tmp = GetRow(m, i); for (let j = tmp.length; j >= 0; j--) { if (tmp[j] <= mid) { get = j + 1; break; } } // 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 < GetRow(m, i).length && m[i][get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min; } function GetRow(matrix, row) { let rowLength = matrix[0].length; let rowVector = Array(rowLength).fill(0); for (let i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector; } // Driver code let r = 3, c = 3; let m = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]; console.log("Median is " + binaryMedian(m, r, c)); OutputMedian is 5 Complexity Analysis:Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time and is performed for each row. And since the numbers will be max of 32 bit, so binary search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 ) operations. Auxiliary Space : O(1) Please refer complete article on Find median in row wise sorted matrix for more details! Comment More infoAdvertise with us K kartik Follow Improve Article Tags : JavaScript Order-Statistics Binary Search statistical-algorithms median-finding +1 More Practice Tags : Binary Search Similar Reads Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q 15+ min read Second Largest Element in an Array Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array.Note: If the second largest element does not exist, return -1. Examples:Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the sec 14 min read Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at 7 min read JSON Web Token (JWT) A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users' identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps an 7 min read Frontend Developer Interview Questions and Answers Frontend development is an important part of web applications, and it is used to build dynamic and user-friendly web applications with an interactive user interface (UI). Many companies are hiring skilled Frontend developers with expertise in HTML, CSS, JavaScript, and modern frameworks and librarie 15+ min read Largest element in an Array Given an array arr. The task is to find the largest element in the given array. Examples: Input: arr[] = [10, 20, 4]Output: 20Explanation: Among 10, 20 and 4, 20 is the largest. Input: arr[] = [20, 10, 20, 4, 100]Output: 100Table of ContentIterative Approach - O(n) Time and O(1) SpaceRecursive Appro 6 min read JavaScript Coding Questions and Answers JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav 15+ min read Top 95+ Javascript Projects For 2025 JavaScript is a lightweight, cross-platform programming language that powers dynamic and interactive web content. From real-time updates to interactive maps and animations, JavaScript brings web pages to life.Here, we provided 95+ JavaScript projects with source code and ideas to provide hands-on ex 4 min read Like