Track Median
def mean(array)
array.inject(0) { |sum, x| sum += x } / array.size.to_f
end
def median(array, already_sorted=false)
return nil if array.empty?
array = array.sort unless already_sorted
m_pos = array.size / 2
return array.size % 2 == 1 ? array[m_pos] : mean(array[m_pos-1..m_pos])
end
puts median([1,2,3,4,5]) # => 3
puts median([5,3,2,1,4]) # => 3
puts median([1,2,3,4]) # => 2.5
puts median([1,1,2,3,4]) # => 2
puts median([2,3,-100,100]) # => 2.5
puts median([1, 1, 10, 100, 1000]) # => 10
Related examples in the same category