void sort_numbers (int& a, int& b, int& c)
{
int arr[3] = {a,b,c};
std::sort(arr,arr+3);
a = arr[0]; b = arr[1]; c = arr[2];
}
If you can't use std::sort (which I suppose could be considered cheating):
1 2 3 4 5 6 7 8 9 10 11 12 13
int min(a,b) { return a < b ? a : b; }
int max(a,b) { return a < b ? b : a; }
void sort_numbers(int& a, int& b, int&c)
{
int arr[3];
arr[0] = min( min( a, b ), c );
arr[2] = max( max( a, b ), c );
arr[1] = (a != arr[0] && a != arr[2]) ? a :
(b != arr[0] && b != arr[2]) ? b : c;
a = arr[0]; b = arr[1]; c = arr[2];
}
@stewbond hey sorry but I can't use arrays because we haven't learned them in class yet do you suggest anything else? Or is there a function to calculate least to greatest?
Thanks!
The function to calculate least to greatest is std::sort, but that uses arrays. The other option is to use the < operator which checks for less-than or greater-than. From there you can sort easily.
I always like to avoid if/elseif/else jumbles because there are so many places in which to make a mistake. While it would be an easy way to solve it, you will probably have an issue, therefore why don't we simply swap variables around?
1 2 3 4 5 6 7 8 9 10 11 12 13
void swap(int& a, int& b)
{ // Alternative implementation:
int temp = a; // a ^= b;
a = b; // b ^= a;
b = temp; // a ^= b;
}
void sort_numbers(int& a, int& b, int& c)
{
if (b < a) swap(a,b);
if (c < b) swap(b,c);
if (b < a) swap(a,b); // Can be optimized further ;)
}
Edit: Actually that worked out way cleaner than I expected!