[Math] Find median of 2 sorted arrays with different lengths

algorithmsmedianorder-statistics

I'm trying to solve the below problem for my assignment but I have no clue how to find the time algorithm. If I have two arrays of same even length then I get, $T(n) = T(n/2) + \theta(n)$
but what about having $m$ and $n$ (not specified odd or even )?

Let $X[1 .. n]$ and $Y[1 .. m]$ be two arrays, containing n and m numbers respectively and they are already in sorted order. Give an $O(\log n + \log m)$ time algorithm to find the median of all $(n+m)$ elements in arrays $X$ and $Y$.

Best Answer

Hint: What you want is to find $p$ such that $X[\frac n2 + p]=Y[\frac m2 -p]$. In the spirit of bisection, start with $p=0$. If $X[\frac n2] \gt Y[\frac m2]$ you need to decrease $p$, while if $X[\frac n2] \lt Y[\frac m2]$ you need to increase $p$.

Related Question