Calculating Median in Ruby

tomgalpin picture tomgalpin · Feb 13, 2013 · Viewed 32.8k times · Source

How do I calculate the median of an array of numbers using Ruby?

I am a beginner and within the progress of my learning I am trying to stick to what has already been taught. Thus the other questions that I've found are beyond my scope.

Here are my notes and my attempt:

  1. sort the array in ascending order.
  2. figure out if it is odd or even in length.
  3. if odd, divide the sorted array length +1 in half. That is the index of the median. Return this value.
  4. if even, find the middle two numbers of the sorted array and divide them in 1/2. Return this value.
  5. Finding the middle two numbers:
  6. divide the sorted array length in half. This is index pt. first middle number.
  7. divide sorted array length + 2 in half. This is the index pt. of the second middle number.
  8. take average of these two middle numbers.

    def median(array)
      ascend = array.sort
      if ascend % 2 != 0
        (ascend.length + 1) / 2.0
      else
        ((ascend.length/2.0) + ((ascend.length + 2)/2.0) / 2.0)
      end
    end
    

Answer

nbarraille picture nbarraille · Feb 13, 2013

Here is a solution that works on both even and odd length array and won't alter the array:

def median(array)
  return nil if array.empty?
  sorted = array.sort
  len = sorted.length
  (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0
end