0

This is a solution for calculating the median value in an array. I get the first three lines, duh ;), but the third line is where the magic is happening. Can someone explain how the 'sorted' variable is using and why it's next to brackets, and why the other variable 'len' is enclosed in those parentheses and then brackets? It's almost like sorted is all of a sudden being used as an array? Thanks!

  def median(array)
    sorted = array.sort
    len = sorted.length
    return ((sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0).to_f
  end

  puts median([3,2,3,8,91])
  puts median([2,8,3,11,-5])
  puts median([4,3,8,11])
1
  • The median is just the "middle" element of the sorted array, hence the sort. The "middle" element, as stated by Benjamin, is the one at the "len/2"-th position. I do however not understand, what happens if the index is not an integer, as must occur either in sorted[(len-1)/2] or sorted[len/2]. May 21, 2013 at 7:04

3 Answers 3

1

Consider this:

[1,2,2,3,4] and [1,2,3,4]. Both arrays are sorted, but have odd and even numbers of elements respectively. So, that piece of code is taking into account these 2 cases.

sorted is indeed an array. You sort [2,3,1,4] and you get back [1,2,3,4]. Then you calculate the middle index (len - 1) / 2 and len / 2 for even / odd number of elements, and find the average of them.

1

Yes, array.sort is returning an array and it is assigned to sorted. You can then access it via array indices.

If you have an odd number of elements, say 5 elements as in the example, the indices come out to be:

(len-1)/2=(5-1)/2=2

len/2=5/2=2 --- (remember this is integer division, so the decimal gets truncated)

So you take the value at index 2 and add them, and then divide by 2, which is the same as the value at index 2.

If you have an even number of elements, say 4,

(len-1)/2=(4-1)/2=1 --- (remember this is integer division, so the decimal gets truncated)

len/2=4/2=2

So in this case, you are effectively averaging the two middle elements 1 and 2, which is the definition of median for when you have an even number of elements.

1
  • Thanks! Very useful. Thank you for the example. I was a little unclear on the indices component being treated as an array argument, and also that you can store nearly any object in an array. Greatly appreciated.
    – ideahed
    May 23, 2013 at 4:53
0

It's almost like sorted is all of a sudden being used as an array?

Yes, it is. On line 2 it's being initialized as being an array with the same elements as the input, but in ascending order (default sort is ascending). On line 3 you have len which is initialized with the length of the sorted array, so yeah, sorted is being used as an array since then, because that's what it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.