2 Replies - 387 Views - Last Post: 16 December 2013 - 01:55 PM Rate Topic: -----

#1 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

I can't figure out how this code works?

Posted 16 December 2013 - 01:39 PM

The following code takes in an array (of even or odd length) and returns the median of that array.

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



I understand everything up to the return statement. Can some describe to me how the return statement plays out with an array = [1, 2, 3, 4, 5]. For example, with an array length of 5 I don't understand how the second half of the numerator of the return statement works. What does it mean to have sorted[5/2] ------ I interpret this as accessing the 2.5th element in the sorted array. I'm confused. Thank you for your assistance!

This post has been edited by xclite: 16 December 2013 - 01:41 PM
Reason for edit:: Adding code tags.


Is This A Good Question/Topic? 0
  • +

Replies To: I can't figure out how this code works?

#2 xclite  Icon User is offline

  • LIKE A BOSS
  • member icon


Reputation: 902
  • View blog
  • Posts: 3,163
  • Joined: 12-May 09

Re: I can't figure out how this code works?

Posted 16 December 2013 - 01:47 PM

*
POPULAR

5 / 2 performs "integer" division, i.e. it returns the integer value of performing the division.
5 / 2 is 2 (not 2.5).

For the array: [1, 2, 3, 4, 5]
sorted[(len -1 ) / 2] is:
sorted[(5 - 1) / 2]
sorted[4 / 2]
sorted[2]
3

sorted[len / 2] is:
sorted[5 / 2]
sorted[2]
3

Consider an even array: [1, 2, 3, 4]
sorted[(len - 1) / 2] is:
sorted[(4 - 1) / 2]
sorted[3 / 2]
sorted[1]
2

sorted[len / 2] is:
sorted[4 / 2]
sorted[2]
3
Was This Post Helpful? 5
  • +
  • -

#3 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

Re: I can't figure out how this code works?

Posted 16 December 2013 - 01:55 PM

You sir are a golden god.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1