private int findValue(int A[], int leftA, int[] B, int leftB, int k) {
if (A.length - leftA > B.length - leftB) {
return findValue(B, leftB, A, leftA, k);
}
if (A.length - leftA == 0) {
return B[k - 1];
}
if (k == 1) {
return Math.min(A[leftA], B[leftB]);
}
int a = Math.min(k / 2, A.length - leftA);
int b = k - a;
if (A[a + leftA - 1] == B[b + leftB - 1]) {
return A[a + leftA - 1];
} else if (A[a + leftA - 1] > B[b + leftB - 1]){
return findValue(A, leftA, B, leftB + b, k - b);
} else {
return findValue(A, leftA + a, B, leftB, k - a);
}
}
public double findMedianSortedArrays(int A[], int B[]) {
int lenA = A.length;
int lenB = B.length;
int sum = lenA + lenB;
if ((sum & 1) == 1) {
return findValue(A, 0, B, 0, sum / 2 + 1);
} else {
return (findValue(A, 0, B, 0, sum / 2) + findValue(A, 0, B, 0, (sum/2 + 1))) / 2.0;
}
}