Java Median median(double[] vals)

Here you can find the source of median(double[] vals)

Description

|vals| is const.

License

Open Source License

Declaration

public static double median(double[] vals) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;

public class Main {
    /**//from w w  w  . j a  v a 2 s. c o m
     * |vals| is const.
     */
    public static double median(double[] vals) {
        if (vals.length == 0) {
            return Double.NaN;
        }

        double[] copy = Arrays.copyOf(vals, vals.length);
        return nonConstMedian(copy);
    }

    /**
     * Use if you don't care if |vals| is altered.
     * Guarenteed to be faster than median().
     */
    public static double nonConstMedian(double[] vals) {
        if (vals.length == 0) {
            return Double.NaN;
        }

        Arrays.sort(vals);

        if (vals.length % 2 == 1) {
            return vals[vals.length / 2];
        } else {
            return (vals[vals.length / 2] + vals[vals.length / 2 - 1]) / 2;
        }
    }
}

Related

  1. median(double[] data, int length)
  2. median(double[] input)
  3. median(double[] l)
  4. median(double[] unsorted)
  5. median(double[] v)
  6. median(double[] values)
  7. median(double[] x)
  8. median(double[] x)
  9. median(double[] x)