find the median of all elements in an array in ruby

To find the median of all elements in an array in Ruby, you can first sort the array and then calculate the median based on the length of the array:

main.rb
arr = [5, 7, 1, 3, 9, 4]

sorted_arr = arr.sort
n = sorted_arr.length

if n % 2 == 0
  median = (sorted_arr[n/2 - 1] + sorted_arr[n/2])/2.0
else
  median = sorted_arr[n/2]
end

puts median # output: 4.5
203 chars
13 lines

Here, we first sort the original array using the sort method in built-in Ruby array module. We then calculate the length of the sorted array and find the median based on the length. If the length of the array is even, we add the middle two numbers and divide by two to find the median; if it's odd, we choose the middle number as the median directly.

related categories

gistlibby LogSnag