Search code examples
javaalgorithmmathlogicmathematical-optimization

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.


Solution

  • 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.