Maximum and minimum of an array using minimum number of comparisons.

 

Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons).


Example 1:

Input:
A = 978, B = 518, C = 300
Output:
518
Explanation:
Since 518>300 and 518<978, so 
518 is the middle element.


Example 2:

Input:
A = 162, B = 934, C = 200
Output:
200
Exaplanation:
Since 200>162 && 200<934,
So, 200 is the middle element.

Constraints:

1<=A,B,C<=109
A,B,C are distinct. 


Solution Hunt:

// Here we are giving the function only.
              
         int middle(int A, int B, int C)
    {
        if((A<B && B<C) || (C<B && B<A))
        return B;
       
       
        else if((B<C && C<A) || (A<C && C<B))
        return C;
    
        else if((C<A && A<B) || (B<A && A<C))
        return A;
        
        
    }









Post a Comment

0 Comments