There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
int m=A.length;
int n=B.length;
int k=0;
if((m+n)%2==0){
k=(m+n)/2;
return (findKthElement(A,0,m,B,0,n,k)+findKthElement(A,0,m,B,0,n,k+1))/2;
}else{
k=(m+n)/2+1;
return findKthElement(A,0,m,B,0,n,k);
}
}
public double findKthElement(int A[],int as, int ae, int B[], int bs, int be, int k){
if (ae-as>be-bs){
return findKthElement(B,bs,be,A,as,ae,k);
}
if(ae-as==0){
return B[k+bs-1];
}
if(k==1){
return Math.min(A[as],B[bs]);
}
int i=Math.min(k/2,ae-as),j=k/2;
if(A[as+i-1]<=B[bs+j-1]){
return findKthElement(A,as+i,ae,B,bs,be,k-i);
}else{
return findKthElement(A,as,ae,B,bs+j,be,k-j);
}
}
}