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)).
#define INT_MIN 0X80000000
#define INT_MAX 0X7FFFFFFF
class Solution {
public:
int fink(int A[], int m, int B[], int n, int k)
{
if (m <= 0)
return B[k-1];
if (n <= 0)
return A[k-1];
int i = (double)m/(m+n)*k - 1;
int j = (k-1) - i;
int Ai_1 = ((i == 0) ? INT_MIN : A[i-1]);
int Bj_1 = ((j == 0) ? INT_MIN : B[j-1]);
int Ai = ((i == m) ? INT_MAX : A[i]);
int Bj = ((j == n) ? INT_MAX : B[j]);
if (Bj_1 <= Ai && Ai <= Bj)
return Ai;
else if (Ai_1 <= Bj && Bj <= Ai)
return Bj;
//A[i] is too small, get rid of lower part of A and higher part of B
if (Ai < Bj)
return fink(A+i+1, m-i-1, B, j, k-i-1);
//B[j] is too small, get rid of higher part of A and lower part of B
else //if(i > 0 && B[j] < A[i-1])
return fink(A, i, B+j+1, n-j-1, k-j-1);
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int total = m + n;
if (total % 2 != 0)
return fink(A, m, B, n, total/2+1);
else
{
double a = fink(A, m, B, n, total/2);
double b = fink(A, m, B, n, total/2+1);
return (a + b)/2.0;
}
}
};