retagged by
1,673 views
0 votes
0 votes
how to find median of 5 distinct values with only 6 comparisons?
retagged by

1 Answer

Best answer
5 votes
5 votes
void Swap(int *a, int *b) {
    int t = *a; *a = *b; *b = t;
}
void Comp(int *a, int *b) {
    if (*a > *b) swap(a,b);
}
int MedianOfFive(int a, int b, int c, int d, int e){
    // makes a < b and c < d
    Comp(&a,&b);             // First comparison
    Comp(&c,&d);             // Second comparison
    
    // eleminate the lowest
    if (c < a) {                    // Third Compariosn
        Swap(&b,&d);
        c = a;
    }

    // gets e in
    a = e;
    
    // makes a < b
    Comp(&a,&b);             // Fourth Comparison
    
    // eliminate another lowest
    // remaing: a,b,d
    if (a < c) {                    //Fifth Comparison
        Swap(&b,&d);
        a = c;
    }
    return Math.Min(d, a);         //Sixth Comparison
}

Reference : I think code is self explanatory. 

selected by

Related questions

0 votes
0 votes
1 answer
1
Hardik Vagadia asked Aug 22, 2016
409 views
How to find the time complexity if finding the median of 2 sorted arrays?
2 votes
2 votes
1 answer
3