Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created September 26, 2014 10:58
Show Gist options
  • Save sreeprasad/8774219df91afc69cbd0 to your computer and use it in GitHub Desktop.
Save sreeprasad/8774219df91afc69cbd0 to your computer and use it in GitHub Desktop.
Median of two arrays of different length
public double findMedianSortedArrays(int A[], int B[]) {
int M= A.length;
int N= B.length;
int mid = (M+N)/2;
if(M<=N)
return median(A,B,Math.max(0,mid-N),Math.min(M-1,mid));
else
return median(B,A,Math.max(0,mid-M),Math.min(N-1,mid));
}
public static double median(int []A, int[]B, int left, int right){
int M = A.length;
int N = B.length;
int mid = (M+N)/2;
if(left>right)
return median(B,A,Math.max(0,mid-M),Math.min(N-1,mid));
int i= (left+right)/2;
int j= mid - i-1;
if(j>=0 && A[i]<B[j])
return median(A,B,i+1,right);
if(j<(N-1) && A[i]>B[j+1])
return median(A,B,left,i-1);
if( (((M+N) & 0x1) > 0 ) || ( (i<=0) && (j<0 || j>=N) ))
return A[i];
if( j<0 || j>=N)
return (A[i]+A[i-1])/2.0;
if(i<=0)
return (A[i]+B[j])/2.0;
return (A[i]+Math.max(B[j],A[i-1]))/2.0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment