Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the highest, lowest, total, average and median from an array in Ruby

lowest = arr.min
highest = arr.max
total = arr.inject(:+)
len = arr.length
average = total.to_f / len # to_f so we don't get an integer result
sorted = arr.sort
median = len % 2 == 1 ? sorted[len/2] : (sorted[len/2 - 1] + sorted[len/2]).to_f / 2

Finding the minimum, maximum, sum and average are trivial and can be done easily in linear time as shown by sepp2k's answer above.

Finding the median is less trivial and the naive implementation (sorting, and then taking the middle element) runs in O(nlogn) time.

There are, however, algorithms that find the median in linear time (such as the median-of-5 algorithm). Others work even for any kind of order statistic (say, you want to find the 5th-smallest element). The problem with those is that you would have to implement them yourself, I know of no Ruby implementation.

O(nlogn) is quite fast already, so if you're not planning on working on huge datasets (and if you will need to sort your data anyway), you'll be fine with that.