1

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.

Community
  • 1
  • 1
Abhinav
  • 238
  • 2
  • 12
  • 1
    Interesting, would be such a maniac found over here? :) – dvvrd Jan 16 '14 at 00:41
  • I guess the number of comparisons you have to do increases exponentially so be prepared for really ugly code. – zapl Jan 16 '14 at 00:55
  • 1
    how about using recursive method? is it considered as _loop_? ;-) – Baby Jan 16 '14 at 00:56
  • @RafaEl let's see, no problem with recursion in case of five numbers. – Abhinav Jan 16 '14 at 01:15
  • 2
    possible duplicate of [given 5 numbers, what is the minimum number of comparisons needed to find the median?](http://stackoverflow.com/questions/1585727/given-5-numbers-what-is-the-minimum-number-of-comparisons-needed-to-find-the-me) According to Knuth's AOCP, the minimum is 6 comparisons. – hardmath Jan 16 '14 at 02:30

2 Answers2

1

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;
}
invisal
  • 10,610
  • 3
  • 29
  • 53
1

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.

Baby
  • 4,924
  • 3
  • 27
  • 50