Search code examples
rubyarraysmedian

Find the median of an array


I wrote some code that returns the median of an unsorted odd numbered array, but it does not return the median of an even numbered array.

I know that in order to find the median of an even numbered array, you have to take the middle two numbers of the array, average them, and that's the median. I can't translate that into usable code. Aside from the obvious verbosity of this code, the issue seems to be with lines 7-8 and I don't see why.

I prefer hints to answers, but if you rather post some fixed code, I can accept that too.

def media(array)
  sorted = array.sort
  list = sorted.length
  if list %2 != 0
    (list + 1) / 2.0
  else
    even = ((list.to_f + 2) / 2) + ((list.to_f / 2)
    return (even/2)
  end
end

Solution

  • I'm going to just jump in with a solution here...

    def median(ary)
      mid = ary.length / 2
      sorted = ary.sort
      ary.length.odd? ? sorted[mid] : 0.5 * (sorted[mid] + sorted[mid - 1])
    end
    

    Edit - I've incorporated .odd? as per BroiSatse's suggestion.