patterncMajor
Given three numbers, find the second greatest of them
Viewed 0 times
threethegreatestnumberssecondfindthemgiven
Problem
I've just coded this for my country's programming Olympiad. I want to know if this method is a good approach in terms of readability and performance. I would also like to know how to improve it.
Note: We can assume all numbers entered are different, positive and smaller or equal to 100.
```
#include
int find_second(int a, int b, int c)
{
if (a > b && b > c)
{
return b;
}
else if (a > c && c > b)
{
return c;
}
else
{
Note: We can assume all numbers entered are different, positive and smaller or equal to 100.
```
#include
int find_second(int a, int b, int c)
{
if (a > b && b > c)
{
return b;
}
else if (a > c && c > b)
{
return c;
}
else
{
Solution
Your
Special numbers that might also be valid data are dangerous. What if the second-largest number happens to be -1?
For a solution that is easier to verify, I recommend this approach.
find_second() function is rather weird. It never finds the second-largest number if it is a. It sometimes finds the second-largest number if it is b or c. I don't know if your program works or not — your main() tries to make up for the deficiencies in find_second() by calling it three times — but the function name is a big fat lie.Special numbers that might also be valid data are dangerous. What if the second-largest number happens to be -1?
For a solution that is easier to verify, I recommend this approach.
min() and max() are trivial to write.int second_largest(int a, int b, int c) {
int smallest = min(min(a, b), c);
int largest = max(max(a, b), c);
/* Toss all three numbers into a bag, then exclude the
minimum and the maximum */
return a ^ b ^ c ^ smallest ^ largest;
}Code Snippets
int second_largest(int a, int b, int c) {
int smallest = min(min(a, b), c);
int largest = max(max(a, b), c);
/* Toss all three numbers into a bag, then exclude the
minimum and the maximum */
return a ^ b ^ c ^ smallest ^ largest;
}Context
StackExchange Code Review Q#132987, answer score: 30
Revisions (0)
No revisions yet.