retagged by
647 views
0 votes
0 votes

I think the median can be found in O(n), because in O(n) we can merge the arrays into a single sorted array and in O(1) we can find the middle element of the array.  Am I correct ??

retagged by

2 Answers

1 votes
1 votes

Using normal approach of merging it is O(n) only.But it can be optimised using divide and conquer technique and hence the complexity can be reduced  to O(logn) . Let us see how to do this :

1) Calculate the medians m1 and m2 of the input arrays ar1[]
   and ar2[] respectively.
2) If m1 and m2 both are equal then we are done.
     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...|_n/2_|])
    b)  From m2 to last element of ar2  (ar2[|_n/2_|...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_|...n-1])
   b)  From first element of ar2 to m2 (ar2[0...|_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 use below formula to get
  the median.
    Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2

In general if one sorted array contains m elements and other contains n elements , then the time complexity of finding median is :

O(logm + logn) . For reference you can visit the following link :

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

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

1 votes
1 votes
logn

algo:

let the two sorted arrays are a1[1...m] a2[1....n]

median of a1=m1

median of a2=m2

1.find m1 and m2.

2. if m1==m2 then  m1 is the median

3 if  m1< m2 then median is between a1[m/2.....m] and a2[0....n/2] so repeat the steps 1,2,3 on a1[m/2....m] and a2[0.....n/2].

4.if  m1> m2 then median is between a2[n/2.....n] and a1[0....m/2] so repeat the steps 1,2,3 on a2[n/2.....n] and a1[0....m/2].

add the base cases accordingly.

time complexity logm + logn as we are  dividing the array each time into half

Related questions

0 votes
0 votes
1 answer
1
gate_dreams asked Jan 27, 2019
353 views
for(i=n, j=0; i>0; i/=2, j+=i)Let val(j) denote the value stored in the variable j after termination of the for loop. Whjch is correct?a. val(j)=theta(logn)b. Val(j)= the...
1 votes
1 votes
2 answers
2
APOORV PANSE asked Jun 1, 2016
2,991 views
Consider the following c fragment : void DAA(n) { int i,j,k,x=0; for (i=1 ; i <=n ; i++) for (j=1 ; j <= i * i ; j++) { if ( j mod i == 0 ) for ( k = 1 ; k <= j ; k++) x=...
1 votes
1 votes
0 answers
3
Ankush Tiwari asked Jul 27, 2016
648 views
T(n)=sqrt(2T(n/2))+logn