 # Best code to understand

#1

double Solution::findMedianSortedArrays(const vector &A, const vector &B) {

``````if(A.size()>B.size())
return findMedianSortedArrays(B,A);
int x=A.size();
int y=B.size();
int low=0;
int high=x;  // for cases like A-[0 23] B-[ ]  low=0 high=0
while(low<=high)
{

int xpartition=low+(high-low)/2;
int ypartition=(x+y+1)/2-xpartition;
//+1 added because of odd and even compatibility
//if xpartition==0 then leftx==INT_MIN
//if xpartition==len then rightx=INT_MAX
int leftx=(xpartition==0)?INT_MIN:A[xpartition-1];
int lefty=(ypartition==0)?INT_MIN:B[ypartition-1];
int rightx=(xpartition==x)?INT_MAX:A[xpartition];
int righty=(ypartition==y)?INT_MAX:B[ypartition];

if(leftx<=righty && lefty<=rightx)
{
if((x+y)%2==0)
{
return ((double)max(leftx,lefty)+min(rightx,righty))/2;
// elements are even thats by avrerage
}
else
{
return max(leftx,lefty);
// 1 3 4  A  left of A->3
// 2 5    B  left of B->2
// ans is max of leftofA and leftofB;
// 1 2 3 4 5  ans is 3
//elements are odd that by left of x and left of y
}
}
else if(leftx>righty)
{
high=xpartition-1;
////we are too far on right side for partitionX. Go on left side.
}
else
{
low=xpartition+1;
////we are too far on left side for partitionX. Go on right side.
}

}
return B;
``````

}