Abhinav
Abhinav

Reputation: 246

Fastest way to find the third largest of five given numbers without using array or loops?

I'm thinking of a logic to find the third largest number of five given numbers without using array or loops but can use conditionals.

Here is Fastest way of finding the middle value of a triple by stephen c. I want to create a logic for 5 numbers to find the third largest.

I want to reduce the comparisons as much as possible to find an optimal solution.

Upvotes: 1

Views: 1653

Answers (2)

Baby
Baby

Reputation: 5092

How about this?

public static int getMiddle(int a, int b, int c, int d, int e){

    int temp;

    if(a>b){
        temp=b; b=a; a=temp;
    }
    if(b>c){
        temp=c; c=b; b=temp;
    }
    if(c>d){
        temp=d; d=c; c=temp;
    }
    if(d>e){
        temp=e; e=d; d=temp;
    }

    if( e>d && d>c && c>b && b>a )
        return c;
    else
        return getMiddle(a, b, c, d, e);
}

Note: Depending on the value of 5 numbers, I strongly think that you cannot reduce the total comparison you have to do, but you can only simplify or optimize the way you do the comparison.

Upvotes: 1

invisal
invisal

Reputation: 11171

Not the most efficient, but at least it is readable.

int median(int a, int b, int c, int d, int e) 
{
    if (a > b) swap(a, b);
    if (a > c) swap(a, c);
    if (a > d) swap(a, d);
    if (a > e) swap(a, e);

    if (b > c) swap(b, c);
    if (b > d) swap(b, d);
    if (b > e) swap(b, e);

    if (c > d) swap(c, d);
    if (c > e) swap(c, e);

    return c;
}

Upvotes: 1

Related Questions