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:
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
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