Web Toolbar by Wibiya

Pages

Thursday, November 17, 2011

Find the median of two arrays without merging them.

Solution #1: Let the two arrays be A[1...n] and B[1...m] and if they are not sorted initially, then sort them using any standard sort in O(n+m) time. below is the code to find the median without merging the arrays,

#include 
#include 

#define SIZEA 10
#define SIZEB 5

int median(int* A, int sizeA, int* B, int sizeB)
{
    int i=0;
    int j=0;

    int med = (sizeA + sizeB)/2+1;

    //2 is added to correct the offset as both the arrays starts at 0
    while((i+j+2) != med)
    {
        if((i < (sizeA-1)) && (j < (sizeB-1))) //none of the arrays reached the end
        {
            if(A[i+1] < B[j+1])
                i++;
            else
                j++;
        }
        else if (i == (sizeA-1)) //array A has reached the end
            j++;
        else if (j == (sizeB-1)) //array B has reached the end
            i++;
    }

    return A[i] > B[j] ? A[i] : B[j];
}

int main()
{
    int A[SIZEA] = {6, 8, 12, 13, 15, 19, 23, 25, 27, 45};
    int B[SIZEB] = {3, 22, 34, 39, 55};
    //int B[SIZEB] = {1, 2, 3, 4, 5};

    printf("Medain of A and B is %d\n", median(A, SIZEA, B, SIZEB));
    return 0;
}

No comments: