sort function

I am trying to write sort function, sort's job is to rearrange a, b, and c so that a is the smallest #, c is the largest #.

I wrote one and it worked but it looks so long and I want to know a short way
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  void sort(double & a, double & b, double & c)
	{
		if (a >= b && b >= c)
			cout <<"Smallest to biggest: "<< c << " " << b << " " << a <<endl;
		else if (a >= c && c >= b)
			cout <<"Smallest to biggest: "<< b << " " << c << " " << a << endl;
		else if (b >= a && a >= c)
			cout <<"Smallest to biggest: "<< c << " " << a << " " << b << endl;
		else if (b >= c && c >= a)
			cout <<"Smallest to biggest: "<< a << " " << c << " " << b << endl;
		else if (c >= a && a >= b)
			cout <<"Smallest to biggest: "<< b << " " << a << " " << c << endl;
		else 
			cout <<"Smallest to biggest: "<< a << " " << b << " " << c << endl;
	}
Compare and swap.

Start with A and B.

If (A > B) then swap A and B. Now (A ≤ B); they are in sorted order.


Now consider C. The three possibilities are:

C ≤ A ≤ B
A ≤ C ≤ B
A ≤ B ≤ C

Think about what tests you need to do to decide how to shuffle values around. I'll give you one:

If (C >= B) then you are all done, and your function can return (because A ≤ B ≤ C).

Good luck!

[edit] BTW, your sort() function should not be writing to cout.
Last edited on
if (a>b) { t = a; a = b; b = t; }
if (b>c) { t = b; b = c; c = t; }
if (a>b) { t = a; a = b; b = t; }
:O)
I don't understand it I have this from my prof
closed account (j3Rz8vqX)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void mySwap(int &first, int &second)
{
    int t = second;
    second = first;
    first = t;
}
void mySort(int &a, int &b, int &c)
{
    if(a>b)
        mySwap(a,b);
    if(a>c)
        mySwap(a,c);
    if(b>c)
        mySwap(b,c);
}
At this point you have to think about what you've been told so far.
Topic archived. No new replies allowed.