算法:两个不同大小的排序数组的中位数

时间:2014-02-16 11:26:31

标签: arrays algorithm median

以下是从here

粘贴的代码

我无法理解它在做什么。我想到了一个简单的算法,可以在合并时找到两个排序数组的中位数。这个想法是比较两个数组的中位数(m1,m2),如果m1 < m2找到右边第一个子阵列的中位数从m1到左边第二个子阵列到m2。以下代码在同一行中执行,但我无法完全理解它。

double findMedian(int A[], int B[], int l, int r, int nA, int nB) {
    if (l>r)
        return findMedian(B, A, max(0, (nA+nB)/2-nA), min(nB, (nA+nB)/2), nB, nA); //What does the min/max do here
    int i = (l+r)/2;
    int j = (nA+nB)/2 – i – 1;
    if (j>=0 && A[i] < B[j])
        return findMedian(A, B, i+1, r, nA, nB);
    else if (j<nB-1 && A[i] > B[j+1])
        return findMedian(A, B, l, i-1, nA, nB);
    else {
        if ( (nA+nB)%2 == 1 ) return A[i];
        else if (i>0) return (A[i]+max(B[j], A[i-1]))/2.0; //I couldn't understand this
        else return (A[i]+B[j])/2.0;
    }
}

double findMedianSortedArrays(int A[], int n, int B[], int m) {
    if (n<m)
        return findMedian(A, B, 0, n-1, n, m);
    else
        return findMedian(B, A, 0, m-1, m, n);
}

代码的第二行有什么作用?除此之外,我无法理解最后else块将如何返回中位数。当i为奇数时,n + m索引会包含中位数吗?

任何帮助,链接或指示表示赞赏。

1 个答案:

答案 0 :(得分:-1)

这是你想要做的伪代码。
我假设ar1ar2是输入数组,两者的大小都是n

算法:

1) Calculate the medians m1 and m2 of the input arrays ar1[] 
   and ar2[] respectively.  
2) If m1 and m2 both are equal then we are done.
     return m1 (or m2)  
3) If m1 is greater than m2, then median is present in one 
   of the below two subarrays.  
    a)  From first element of ar1 to m1 (ar1[0...|_n/2_|])  
    b)  From m2 to last element of ar2  (ar2[|_n/2_|...n-1])  
4) If m2 is greater than m1, then median is present in one      
   of the below two subarrays.  
   a)  From m1 to last element of ar1  (ar1[|_n/2_|...n-1])  
   b)  From first element of ar2 to m2 (ar2[0...|_n/2_|])  
5) Repeat the above process until size of both the subarrays 
   becomes 2.  
6) If size of the two arrays is 2 then use below formula to get   
  the median.  
    Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2    

现在,您可以将其编码为您选择的任何语言。

希望这有帮助!

相关问题