2011 found two arrays median

Thought: seeking respectively A, B of the median, median if a = bar, then a or b of the request, otherwise, discarding a, b where the smallest half smaller sequences, while discarding greater where half larger sequence, requires two to discard the same number of elements, repeating the process until the two sequences containing only one element up, the smaller is the median ask.

Code:

int search(int a[],int b[],int n)
{
    int s1,e1,mid1,s2,e2,mid2;
    s1=0;e1=n-1;s2=1;e2=n-1;
    while(s1!=e1||s2!=e2)
    {
        mid1=(s1+e1)/2;
        mid2=(s2+e2)/2;
        if(a[mid1]==b[mid2])return a[mid1];
        if(a[mid1]<b[mid2])
        {
            if((s1+e1)%2==0 ) // if the number is an odd number of elements 
            { 
                S1 = MID1; // discarded before the intermediate point and retain a portion of the intermediate point 
                E2 = MID2; // discard portion after an intermediate point b and intermediate points reserved 
            }
             the else 
            { 
                S1 = + MID1 1 ; // discard portion and a middle point before a midpoint 
                E2 = MID2; // discard previously reserved portion b and the midpoint midpoint 
            } 

        } 
        the else 
        { 
             IF ((S1 + E1)% 2 == 0 ) // if the element The number is an odd number 
            { 
                E1 = MID1;// discarded after a middle point portion and retain an intermediate point 
                s2 = MID2; // discard previously reserved portion b and the midpoint midpoint 
            }
             the else 
            { 
                E1 = MID1 + . 1 ; // discarded before the intermediate point and retain a portion of the intermediate point 
                s2 = MID2; // discard intermediate point b and intermediate points before 
            } 
        } 

    } 
    return (A [S1] <b [S2]? A [S1]: b [S2]); 
}

 

Guess you like

Origin www.cnblogs.com/yangmenda/p/11707755.html