Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the largest and smallest of 3 values with fewest comparisons?

This is a simple introduction course question. I have to write a program that asks the user to input 3 numbers, and determines the largest and smallest number.

I need to only use if statements.

This is what I tried so far: which required 4 comparisons.

int x, y, z;
int smallest, largest; 
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;

smallest = x;
largest = x;

if (y > largest) 
        largest = y;
if (z > largest)
        largest = z;
if (y < smallest)
        smallest = y;
if (z < smallest)
        smallest = z;

cout << "largest: " << largest << ", and smallest: " << smallest << endl;   

My question is: Is it possible to only use 3 comparisons, or less? I think when y > largest, it also tells us something else as well?

like image 420
George Avatar asked May 24 '13 21:05

George


2 Answers

The issue with your code is that you toss out a lot of information. In "challenges" such as these, you have to make the most of what you have. So when you say, for example

if (y > largest) 

don't just treat the true case. Also try to reason about the case when the condition doesn't hold.

if ( x < y )
{
    smallest = x;
    biggest = y;
}
else
{
    smallest = y;
    biggest = x;
}

if ( z < smallest )
   smallest = z;
else if ( z > biggest )
   biggest = z;

This contains only 3 comparisons.

like image 134
Luchian Grigore Avatar answered Oct 31 '22 00:10

Luchian Grigore


Why are you checking if (y < smallest)? At this point in the flow, smallest must be x, but you've already checked if y > x in the first condition (if (y > largest)), so the third condition is redundant.

like image 35
Ilya Kogan Avatar answered Oct 31 '22 00:10

Ilya Kogan