3 Replies Latest reply: May 26, 2007 4:05 PM by 807600 RSS

    Finding Median of 5 Integers

    807600
      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
          807600
          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:
          http://forum.java.sun.com/thread.jspa?threadID=5175758&start=0&tstart=0

          ;)

          Message was edited by:
          helloWorld
          • 2. Re: Finding Median of 5 Integers
            807600
            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
              807600
              Hey thanks. It works like a charm.

              Thanks for helping a noobie coder.