Find the median of an array

前端 未结 4 1576
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  北海茫月
    2021-01-25 18:04

    Here is the answer:

    def get_median(sub_a)
        result = -1
        size = sub_a.size
        if size == 0
            result = 0
        elsif size == 1
            result = sub_a[0]
        elsif size == 2
            result = get_average(sub_a[0], sub_a[1])
        else
            sorted_a = sub_a.sort
            index = size / 2
            if size % 2 == 0
                result = get_average(sorted_a[index - 1], sorted_a[index]);
            else 
                result = sorted_a[index];
            end
        end
    
        '%0.01f' % result
    end
    

提交回复
热议问题