Finding the median value of an array?

后端 未结 9 1290
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 14:58

I was wondering if it was possible to find the median value of an array? For example, suppose I have an array of size nine. Would it possible to find the middle slot of this

相关标签:
9条回答
  • 2020-12-03 15:33

    Assuming the array x is sorted and is of length n:

    If n is odd then the median is x[(n-1)/2].
    If n is even than the median is ( x[n/2] + x[(n/2)-1] ) / 2.

    0 讨论(0)
  • 2020-12-03 15:33

    In C++, you can use std::nth_element; see http://cplusplus.com/reference/algorithm/nth_element/.

    0 讨论(0)
  • 2020-12-03 15:34

    In the case of Java, dividing by 2.0 is enough to cast int to double:

     return n%2 == 0 ? (all[n/2] + all[n/2-1])/2.0 : all[(n-1)/2];
    

    The first condition checks if the value is even.

    0 讨论(0)
提交回复
热议问题