Originally Posted by

**lizartt**
Implement a java method with three local int variables A,b,c

Sort three of the values in ascending order by comparing and exchanging their values.

// A "bubble sort" with three numbers
Given numbers a, b, c
IF a IS GREATER THAN b THEN
SWAP a AND b
END IF
// Now we know that a is larger than b, but we don't
// know whether or not b is larger than c
//
// So...
IF b IS GREATER THAN c THEN
SWAP b and c
END IF
// Now, at this point we know that c contains the largest of the
// three values.
// We don't know whether or not a is larger than b any more
// since b may have changed from what it was after the first
// step.
//
// So...
IF a IS GREATER THAN b
THEN
SWAP a AND b
END IF
//Taa-daa

Try the following six cases with pencil and paper. Go through the steps of the algorithm shown above. Really. Do it with pencil and paper.

Don't just look at then and nod your head and say, "Oh, yeah. Now I get it." Write down all of the steps. There are only six sorting sequences with different values of a, b, c, and each case has only two steps. Invest the time to come to a complete understanding. (You will thank me later...)

a b c

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1
Just for kicks, you can even try with repeated numbers to make sure it always works

a b c

1 1 2

1 2 1

2 1 1

1 1 1
Now, you have covered all possible sort sequences for three variables. The Java that comes from a direct implementation of the above pseudo-code is "trivial." (You have already implemented the first step, right?)

Test the code with the same cases that you worked out with pencil and paper (or anything else that covers all possible ordering of three variables).

Cheers!

Z