Java Median median(double[] data, int length)

Here you can find the source of median(double[] data, int length)

Description

calculates the median of a number array

License

Open Source License

Parameter

Parameter Description
data the array of data
length the searchable length

Return

the median of a number array. 0 on zero length

Declaration

public static double median(double[] data, int length) 

Method Source Code

//package com.java2s;
/*/*from w w w.j  av a  2 s.  c  om*/
 * Copyright 2013 Rub?n H?ctor Garc?a <raiben@gmail.com>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Arrays;

public class Main {
    /**
     * calculates the median of a number array
     *
     * @param data the array of data
     * @param length the searchable length
     * @return the median of a number array. 0 on zero length
     */
    public static double median(double[] data, int length) {
        if (length > data.length) {
            length = data.length;
        }
        if (length == 0) {
            return 0;
        }
        double[] b = new double[length];
        System.arraycopy(data, 0, b, 0, length);
        Arrays.sort(b);

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

Related

  1. median(double[] a)
  2. median(double[] arr)
  3. median(double[] array)
  4. median(double[] array)
  5. median(double[] data)
  6. median(double[] input)
  7. median(double[] l)
  8. median(double[] unsorted)
  9. median(double[] v)