snippetcppModerate
Sort three input values by order
Viewed 0 times
threeorderinputvaluessort
Problem
This is a program to sort three inputted integers in order, from least to greatest. I would like to have it reviewed.
#include
void Sort(int &a, int &b, int &c){
if(a>b){
int tmp = a;
a = b;
b = tmp;
}
if(a>c){
int tmp = a;
a=c;
c = tmp;
}
if(b>c){
int tmp = b;
b=c;
c=tmp;
}
return;
}
int main(){
std::cout > num1 >> num2 >> num3;
int output1 = num1;
int output2 = num2;
int output3 = num3;
Sort(output1,output2,output3);
std::cout << num1 << " " << num2 << " " << num3 << " "
<< " in sorted order: ";
std::cout << output1 << " " << output2 << " " << output3 << std::endl;
return 0;
}Solution
Things you should change:
-
-
Pay attention to the spacing between the
-
You don't have to
This is also a great opportunity for you to learn about C++ templates. I will suggest you a base implementation that you can study, test, and better understand the awesomeness of this language feature:
Just as in the example provided by @EngieOP, I've added a swap function to reuse more code.
I've also better separated common code by moving the conditional inside the swap function (
-
Sort() is explicitly returning at the end (return;). The return statement is implicit once you reach the end of a void function, so should not appear.-
Pay attention to the spacing between the
= sign. In some places you have b=c; while in others you have a = b; Be consistent with the spacing. I suggest the latter, as it seems more readable to me.-
You don't have to
return 0 from main. For main(), the return zero is implicit if not added.This is also a great opportunity for you to learn about C++ templates. I will suggest you a base implementation that you can study, test, and better understand the awesomeness of this language feature:
template
void swap_if_greater(T& a, T& b)
{
if (a > b)
{
T tmp(a);
a = b;
b = tmp;
}
}
template
void sort(T& a, T& b, T& c)
{
swap_if_greater(a, b);
swap_if_greater(a, c);
swap_if_greater(b, c);
}Just as in the example provided by @EngieOP, I've added a swap function to reuse more code.
I've also better separated common code by moving the conditional inside the swap function (
swap_if_greater()), since it is common to all inputs. sort() is now a template function, meaning is can operate on any type, including int, float, double, char, ... It is a generic function, just as many of the functions in the standard C++ library. This concept promotes great code reuse and low redundancy of functionality.Code Snippets
template<typename T>
void swap_if_greater(T& a, T& b)
{
if (a > b)
{
T tmp(a);
a = b;
b = tmp;
}
}
template<typename T>
void sort(T& a, T& b, T& c)
{
swap_if_greater(a, b);
swap_if_greater(a, c);
swap_if_greater(b, c);
}Context
StackExchange Code Review Q#64758, answer score: 12
Revisions (0)
No revisions yet.