Suppose we are given a $n\times n$ matrix that is sorted row-wise and column-wise. We want to find the median in $\mathcal{O}(n\log{n})$.
This is my approach:
We know median is such element that is greater than exactly $\lfloor\frac{n^2-1}{2}\rfloor$ elements.
In such matrix, we always know that minimum value is the first element and the maximum value is the last element. So we declare and initialize two variables $\texttt{min}$ and $\texttt{max}$. Then we put $\texttt{mid} = \frac{\texttt{min}+\texttt{max}}{2}$. Afterwards, we're going to count the number of elements that are lower than $\texttt{mid}$ using binary search. For each row, the binary search can be done in $\mathcal{O}(\log{n})$ and we're doing it on $\mathcal{O}(n)$ rows. So this part takes $\mathcal{O}(n\log{n})$ time. If number of smaller elements than $\texttt{mid}$ is lower than $\lfloor\frac{n^2-1}{2}\rfloor$, then we put $\texttt{min}=\texttt{mid}+1$. Otherwise we put $\texttt{max}=\texttt{mid}$. Then recurse with new $\texttt{min}$ and $\texttt{max}$ values. The condiction to stop is when $\texttt{min}\geq\texttt{max}$. Then we return $\texttt{min}$.
Time complexity analysis:
According to the algorithm I explained, the recurrence relation should be:
$$T(n)=T(\frac{n}{2})+\mathcal{O}(n\log{n}).$$
Using Master's Theorem, we can conclude $T(n)=\mathcal{O}(n\log{n})$. So we're done.
I want to know:
- Is my algorithm correct?
- Is the time complexity analysis correct?
- I know the algorithm is not explained accurate enough. For example I don't know I should count elements that are strictly smaller than $\texttt{mid}$, or I should also count elements that are equal to $\texttt{mid}$. Also when checking if the smaller elements are $<$ or $\leq $ than $\lfloor\frac{n^2-1}{2}\rfloor$.
Any helps are immensley valuable to me.
EDIT.
I found a problem in the algorithm. What if $\texttt{min}$ is not an element existing in the array? How can I solve the problem?