1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use na::{self, RealField};

/// Computes the median of a set of values.
#[inline]
pub fn median<N: RealField>(vals: &mut [N]) -> N {
    assert!(vals.len() > 0, "Cannot compute the median of zero values.");

    vals.sort_by(|a, b| a.partial_cmp(b).unwrap());

    let n = vals.len();

    if n % 2 == 0 {
        (vals[n / 2 - 1] + vals[n / 2]) / na::convert(2.0)
    } else {
        vals[n / 2]
    }
}