You see, I\'ve self-taught myself C++ (not completely, I\'m still procrastinating -_-). So, now I started university and they\'re teaching C and they made us do a program of
The whole point of the classroom problem that requests finding the largest and the smallest simultaneously is to teach you to extract maximum valuable information from each comparison.
For example, if you know that a > b
is true, from that single comparison you should realize that a
is no longer candidate for the smallest and should no longer participate in any comparisons dedicated to finding the smallest. And, at the same time, you should realize that b
is no longer candidate for the largest. With 4 numbers, two tests a > b
and c > d
already clearly separate the numbers into two independent classes: two candidates for the largest and two candidates for the smallest. The rest is straightforward.
In other words, the whole idea is to find the extreme values in parallel, using the information provided by each comparison to further the task of finding both the smallest and the largest value.
if (first > second) {
int t = first; first = second; second = t;
}
if (third > fourth) {
int t = third; third = fourth; fourth = t;
}
/* Now 'first' and 'third' are candidates for the smallest,
while 'second' and 'fourth' are candidates for the largest */
int min = first < third ? first : third;
int max = second > fourth ? second : fourth;
As you can see, this requires only four comparisons to find both numbers.
Note that the above code gives you the values of the smallest and the largest, but it does not tell you the original "index" of the number that provided each value. It is not immediately clear whether it is really necessary. The text of your question says nothing about that, while the code sample you provided implements it. In any case, it is not difficult to update the above code to make it to "track" the origins of the numbers.