Created
March 26, 2013 22:52
-
-
Save TalkativeTree/5250053 to your computer and use it in GitHub Desktop.
Finding the median of an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#median([1,2,3]) # => 2 | |
#median([4.5, 0, -1]) # => 0 | |
#median([-100, 100]) # => 0.0 | |
def median(array) | |
if array.length.odd? | |
array.fetch(array.length / 2) | |
elsif array.length.even? | |
(array.fetch(array.length / 2 -1) + array.fetch(array.length / 2)) / 2.0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment