 ronith
6/6/2018 - 6:29 AM

## Median of two sorted arrays of same size

There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)).

Algorithm :

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, ar2) + min(ar1, ar2))/2 Examples :

ar1[] = {1, 12, 15, 26, 38} ar2[] = {2, 13, 17, 30, 45} For above two arrays m1 = 15 and m2 = 17

For the above ar1[] and ar2[], m1 is smaller than m2. So median is present in one of the following two subarrays.

[15, 26, 38] and [2, 13, 17] Let us repeat the process for above two subarrays:

``````m1 = 26 m2 = 13.
``````

m1 is greater than m2. So the subarrays become

[15, 26] and [13, 17] Now size is 2, so median = (max(ar1, ar2) + min(ar1, ar2))/2 = (max(15, 13) + min(26, 17))/2 = (15 + 17)/2 = 16

``````#include <iostream>
using namespace std;

int median(int l,int r){
return l+(r-l)/2;
}

int find(int a[],int b[],int l1,int r1,int l2,int r2){
if (r1-l1 == 1 && r2-l2 ==1){
int min,max;
if (a[l1]>b[l2])
max=a[l1];
else
max=b[l2];
if (a[r1]<b[r2])
min=a[r1];
else
min=b[r2];
return (min+max)/2;
}
else{
int m1=median(l1,r1), m2=median(l2,r2);
if (a[m1]==b[m2])
return m1;
if (a[m1]>b[m2])
return find(a,b,l1,m1,m2,r2);
return find(a,b,m1,r1,l2,m2);
}
}

int main(){
int n,m;
cin>>n>>m;
int a[n],b[m];
for(int i=0;i<n;i++)
cin>> a[i];
for(int i=0;i<m;i++)
cin>> b[i];

int j = find(a,b,0,n-1,0,m-1);
cout<<"median is:"<<j;
}
``````