carolineartz

1/12/2014 - 4:15 AM

Exercise: Calculating the median of an array of numbers Write a method median which takes an Array of numbers as its input and returns the median value.

```
# CALCULATE THE MEDIAN OF AN ARRAY OF NUMBERS
# PSEUDOCODE
# INPUT: array of numbers
# OUPUT: the median number of the elements of the input array
# STEPS: sort the array
# determine if the array has one or two middle values by checking
# if the length is even or odd
# if there is an odd length, return the value of the middle element
# otherwise return the average of the two middle elements' values
# INITIAL CODE:
def median(array)
array.sort!
n = array.length
if n % 2 != 0
return array[(n - 1) / 2]
else
return (array[n/2] + array[(n/2)-1]) / 2.0
end
end
# REFACTORED CODE:
def median(array)
mid = array.length / 2
if array.length.odd?
array.sort![mid]
else
(array.sort![mid - 1] + array[mid]) / 2.0
end
end
# REVIEW/REFLECT My approach for this problem was pretty solid, I believe. I
# can't figure out much more to refactor; most solutions I have found within
# DBC and outside have pretty simliar logic and use of methods. I did find out
# about this little #odd? method, and its complement #even?, and now I can
# avoid using the modulus technique for testing even/odd. I'll have to
# remember these!
```