3 Replies Latest reply on May 26, 2007 9:05 PM by 807600

# Finding Median of 5 Integers

I need to find the median of 5 integers for a program. I have a conglomeration of IF statements where I am sorting the numbers using Math.min and Math.max. If someone has a slightly more elegant way please post here.
• ###### 1. Re: Finding Median of 5 Integers
Hehe, with 5 numbers I can make a whole sentence!!

You can modify this :)
``````public static  int median(int a, int b, int c){
return (

a > b & a
<
c
) ? a : (

a >c &a <
b   )   ?
a   :   (

c > a & c
<
b

)? c :( c
>    b
& c  <

a  )?c:b;;;
}``````
You can also find some other really cool approaches here:

;)

Message was edited by:
helloWorld
• ###### 2. Re: Finding Median of 5 Integers
You should use an array and take a look at Arrays.sort(). This is one way of doing it, if-else and ternary are no good. If this is an assignment then you should look to deliver code that will work for any number of values even if your assignment works only with five numbers, the same algorithm should work with any amount.

If you take a look at using arrays in your approach and then you are stuck then post back. People like to see your efforts here before they will help, especially with what look like homework.

Cheers
• ###### 3. Re: Finding Median of 5 Integers
Hey thanks. It works like a charm.

Thanks for helping a noobie coder.