3 number sorting?

Can someone check my code to see if it works. I can't get it to output anything.. (it does compile)
I'm not sure that my swap is working properly.
Thanks!


#include <iostream>

using namespace std;

void myswap(int&, int&);

int main(int argc, char** argv) {

int var1, var2, var3, hold;

cout << "Enter three numbers ";
cin >> var1 >> var2 >> var3;

if (var1 > var2)
{
myswap(var1, var2);
}
if (var3 <= var1)
{
cout << var3 << " " << var1 << " " << var2 << endl;
}
else if (var3 >= var1)
{
if(var3 < var2)
{
cout << var1 << " " << var3 << " " << var2 << endl;
}
}
else
cout << var1 << " " << var2 << " " << var3 << endl;


return 0;
}

void myswap(int& var1, int& var2)
{
int hold;

hold= var1;
var1 = var2;
var2 = hold;

}
Last edited on
hold= var1
var1 = var2;
var2 = hold;
myswap() is incorrect.

There's at least one control path in your program where nothing is printed.
wwwiii that is how to swap the varaibles. But he has a few other errors. 1) he has a return in a void function. 2) he is not modifying the values being passed into the function he is modifying the local copies of them. He should be passing by reference.
Thanks, I fixed those problems, it's still not outputting in ascending order like I want it to.. It isn't outputting a value at all?
You make things too complicated. Try the following

Compare (and swap) first with second.
Compare (and swap) second with third.
Compare (and swap) first with second.

Now print first-second-third.

All comparisons should be "less than" for example.
Your code seems fine to me.

As per helios "There's at least one control path in your program where nothing is printed."

You are not printing the output when u are inputting numbers already in ascending order. you can write else part for if(var3 < var2) for that case.

Your code can be simplified as well. Here is a simplified version of your code if it helps
/**********************************************************/
int var1, var2, var3;

cout << "Enter three numbers ";
cin >> var1 >> var2 >> var3;

if (var1 > var2) {
myswap(var1, var2);
}

if( var1 > var3 ) {
myswap(var1, var3);
}

if( var2 > var3 ) {
myswap(var2, var3);
}

cout << var1 << " " << var2 << " " << var3 << endl;
/**********************************************************/
Topic archived. No new replies allowed.