GATE CSE
First time here? Checkout the FAQ!
x
+6 votes
231 views

It takes $O(n)$ time to find the median in a list of $n$ elements, which are not necessarily in sorted order while it takes only $O(1)$ time to find the median in a list of $n$ sorted elements. How much time does it take to find the median of $2n$ elements which are given as two lists of $n$ sorted elements each?

  1. $O (1)$
  2. $O \left(\log n\right)$ but not $O (1)$
  3. $O (\sqrt{n})$ but not $O \left(\log n\right)$
  4. $O (n)$ but not $O (\sqrt{n})$
  5. $O \left(n \log n\right)$ but not $O (n)$
asked in Algorithms by Veteran (38.7k points)  
edited by | 231 views

Aspi R Osa ji,

Very good observation. But i think question needs some correction. Because  in sorted list they are finding median in O(1) time (or their list has properties simillar to array).

1 Answer

+11 votes
Best answer

1) Calculate the medians m1 and m2 of the input arrays ar1[]
   and ar2[] respectively.
2) If m1 and m2 both are equal.
     return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
   of the below two subarrays.
    a)  From first element of ar1 to m1 (ar1[0 to n/2])
    b)  From m2 to last element of ar2  (ar2[n/2 to n-1])
4) If m2 is greater than m1, then median is present in one    
   of the below two subarrays.
   a)  From m1 to last element of ar1  (ar1[n/2 to n-1])
   b)  From first element of ar2 to m2 (ar2[0 to n/2])
5) Repeat the above process until size of both the subarrays
   becomes 2.
6) If size of the two arrays is 2 then
  the median.
    Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
Time complexity O(logn)

http://www.geeksforgeeks.org/median-of-two-sorted-arrays/

answered by Veteran (15.1k points)  
edited by
its given lists. why can we use arrays then?

Aspi R Osa ji,

Very good observation. But i think question needs some correction. Because  in sorted list they are finding median in O(1) time (or their list has properties simillar to array).



Top Users Sep 2017
  1. Habibkhan

    6362 Points

  2. Warrior

    2234 Points

  3. Arjun

    2212 Points

  4. nikunj

    1980 Points

  5. manu00x

    1726 Points

  6. SiddharthMahapatra

    1718 Points

  7. Bikram

    1716 Points

  8. makhdoom ghaya

    1660 Points

  9. A_i_$_h

    1552 Points

  10. rishu_darkshadow

    1512 Points


25,991 questions
33,561 answers
79,414 comments
31,029 users