# Thread: Sort 3 int's WITHOUT an aray.

1. Member
Join Date
Mar 2010
Posts
7
Rep Power
0

## 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!

2. Senior Member
Join Date
Jun 2008
Posts
2,571
Rep Power
11
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).

3. Member
Join Date
Mar 2010
Posts
7
Rep Power
0
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!

4. Also have a look at this little trickery:

Java 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

5. Member
Join Date
Mar 2010
Posts
7
Rep Power
0
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

6. Member
Join Date
Mar 2010
Posts
8
Rep Power
0
U can use recursion for this
Java 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);
}

}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•