private double compute()

in commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Median.java [247:288]


    private double compute(int[] values, int from, int to) {
        final int[] x;
        final int start;
        final int end;
        if (copy) {
            x = Statistics.copy(values, from, to);
            start = 0;
            end = x.length;
        } else {
            x = values;
            start = from;
            end = to;
        }
        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
                if (x[start + 1] < x[start]) {
                    final int 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]);
    }