in commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Median.java [171:206]
private double compute(double[] values, int from, int to) {
// Floating-point data handling
final int[] bounds = new int[2];
final double[] x = nanTransformer.apply(values, from, to, bounds);
final int start = bounds[0];
final int end = bounds[1];
final int n = end - start;
// Special cases
if (n <= 2) {
switch (n) {
case 2:
// Sorting the array matches the behaviour of Quantile for n==2
// Handle NaN and signed zeros
if (Double.compare(x[start + 1], x[start]) < 0) {
final double t = x[start];
x[start] = x[start + 1];
x[start + 1] = t;
}
return Interpolation.mean(x[start], x[start + 1]);
case 1:
return x[start];
default:
return Double.NaN;
}
}
// Median index (including the offset)
final int m = (start + end) >>> 1;
// Odd
if ((n & 0x1) == 1) {
Selection.select(x, start, end, m);
return x[m];
}
// Even: require (m-1, m)
Selection.select(x, start, end, new int[] {m - 1, m});
return Interpolation.mean(x[m - 1], x[m]);
}