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:
- sort the array in ascending order.
- figure out if it is odd or even in length.
- if odd, divide the sorted array length +1 in half. That is the index of the median. Return this value.
- if even, find the middle two numbers of the sorted array and divide them in 1/2. Return this value.
- Finding the middle two numbers:
- divide the sorted array length in half. This is index pt. first middle number.
- divide sorted array length + 2 in half. This is the index pt. of the second middle number.
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