-
Sorting 3 ints
Hallo,
I have a homework question where I have to sort 3 ints. I have done it, but I think there is a better way to do it?
Anyone want to take a look?
Code:
int a,b,c;
// Check if 'a' is the smallest one
if( (a < b) && (a < c) )
{
cout << "A is smalles" << endl;
// If 'a' is the smallest, check which is the biggest
if(c < b)
cout << "B is biggest" << endl;
else
cout << "C is biggest" << endl;
}
// Check if 'b' is the smallest one
if( (b < a) && (b < c) )
{
cout << "B is smalles" << endl;
// If 'a' is the smallest, check which is the biggest
if(a < c)
cout << "C is biggest" << endl;
else
cout << "A is biggest" << endl;
}
// Check if 'c' is the smallest one
if( (c < a) && (c < b) )
{
cout << "C is smalles" << endl;
// If 'a' is the smallest, check which is the biggest
if(a < b)
cout << "B is biggest" << endl;
else
cout << "A is biggest" << endl;
}
I cant use any of the sort functions.
-
For comparing only 3 values, you aren't going to find a better way than just checking the possibilities. But you can imagine the pain of doing this for, say, 10 values instead of 3. And it would be completely impossible if it had to work for any number of values.
So, I'd say your solution is fine.
-
Maybe use else if's instead of if when testing for the smallest. It'll stop unnecessary checks.
-
If by sorting it is meant that in the end a would contain the smallest value, b the middle one and c the largest (you are supposed to swap something), then 3 values could sorted with exactly 3 comparisions.
Just do the same steps that a bubble-sort would do:
Code:
void bubble_sort(int *array, int count)
{
for (int i = 0; i != count - 1; ++i) {
for (int j = 1; j != count - i; ++j) {
if (array[j-1] > array[j])
std::swap(array[j-1], array[j]);
}
}
}
-
Pick any comparison as your first one, say a < b
If that is true, what are the possibilities? cab, or acb, or abc.
So, now check for the first possibility by testing if c < a. If so, you're done.
If not, then try the second possibility by testing if c < b. If so it's a acb, otherwise its abc.
Now assume a is not less than b (the else case)
What are the possibilities? cba, or bca, or bac.
So, now check for the first possibility by testing if c < b. If so, you're done.
If not, then try the second possibility by testing if c < a. If so it's a bca, otherwise its bac.
That's actually the whole thing there in pseudocode! No more than 3 tests are done to determine the resulting ordering, and sometimes even 2 is enough.