# I can't figure out how this code works?

Page 1 of 1

## 2 Replies - 511 Views - Last Post: 16 December 2013 - 01:55 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=336679&amp;s=8ac22929c8e3b0b32b006a410477ecff&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 heaphyg

Reputation: 4
• 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

• I wrote you an code

Reputation: 992
• Posts: 3,485
• 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

### #3 heaphyg

Reputation: 4
• 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.