Find the median of an array

前端 未结 4 1582
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 17:25

I wrote some code that returns the median of an unsorted odd numbered array, but it does not return the median of an even numbered array.

I know that in order to find

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 18:07

    I'm going to just jump in with a solution here...

    def median(ary)
      mid = ary.length / 2
      sorted = ary.sort
      ary.length.odd? ? sorted[mid] : 0.5 * (sorted[mid] + sorted[mid - 1])
    end
    

    Edit - I've incorporated .odd? as per BroiSatse's suggestion.

提交回复
热议问题