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
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.
In C++, you can use std::nth_element
; see http://cplusplus.com/reference/algorithm/nth_element/.
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.