# Sort 3 int's WITHOUT an aray.

• 03-04-2010, 05:09 AM
Sdannenberg3
Sort 3 int's WITHOUT an aray.
Hello everyone, I am new to the Java Forums (and Java itself) and so far, this site has been GREAT! I have been reading through some threads before, but now I need to ask a question so I thought it was time to create a profile!

On an assignment I am doing, the professor has asked us to write a method that takes 3 integers as its input parameters (int a, int b, int c), sort the int's in order, and return a string with the numbers in order. AND I CAN NOT USE AN ARRAY! I was going good until i read that part lol.

EXAMPLE: if (199, 8, 23) is passed, it should return "8 23 199".

So how would I do this? I just need help with the physical sorting part.

I started off with this just to get the first number, but it just doesnt feel right. There has to be a better way? And if this is the way, how would I get the second and third number in the correct order (least to highest)

public static String inOrder(int a, int b, int c){
String s = ("");
if (a < b && a < c){
s += (a + " ");
}
else if (b < a && b < c){
s += (b + " ");
}
else{
s += (c + " ");
}
return s;
}

Thanks in advanced for any help!
• 03-04-2010, 08:06 AM
You need a fourth variable to use as a swap (there are other ways, but this is the easiest). Then compare a and b and swap them if they are in the wrong order. Then compare b and c and swap them if they are in the wrong order. Then compare a and b again and swap them if they are in the wrong order (as c might have been the smallest).
• 03-04-2010, 08:46 AM
Sdannenberg3
You sir, are a genius! I was trying SOOO hard to do this one, but I couldnt figure it out without an array. (I hate how my professor is making us backtrack and not letting us use stuff that we learned >:-|

Thanks again! this should work perfectly!
• 03-04-2010, 09:15 AM
JosAH
Also have a look at this little trickery:

Code:

int a, b, c; // to be sorted
int sa, sb, sc; // the sorted values

// here goes:
sa= Math.min(Math.min(a, b), c);
sc= Math.max(Math.max(a, b), c);
sb= a^b^c^sa^sc;

This only works for ints of any size ...

kind regards,

Jos
• 03-04-2010, 09:25 AM
Sdannenberg3
Ohh wow! thats a cool way of going about it! I should have been more specific though. When i said I can use an array, I meant to say I cant use ANYTHING other than .length(), .charAT, and .substring() from the string class :(

He is trying to make use think outside the box a little, and boy is it working! :D
• 03-04-2010, 11:21 AM
ziaf
U can use recursion for this
Code:

private String test1(int a, int b, int c) {
if(a <= b ) {
if(b <= c) {
return a+" "+b+" "+c;
} else {
return test1(a,c,b);
}
} else {
return test1(b,a,c);
}

}