Java List Median getMedianValue(List nums)

Here you can find the source of getMedianValue(List nums)

Description

Gets the median value from a list of numbers.

License

Open Source License

Parameter

Parameter Description
nums the list of values

Return

the median

Declaration

public static int getMedianValue(List<Integer> nums) 

Method Source Code


//package com.java2s;
/*//from ww w  . ja  va 2 s  .  com
 * Copyright 2008, Myron Marston <myron DOT marston AT gmail DOT com>
 *
 * This file is part of Fractal Composer.
 *
 * Fractal Composer 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.
 *
 * Fractal Composer 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 Fractal Composer.  If not, see <http://www.gnu.org/licenses/>. 
 */

import java.util.*;

public class Main {
    /**
     * Gets the median value from a list of numbers.  This is the value that has
     * the same number of values above it and below it when the list has
     * been sorted.  For a list that has an even number of entries, this method
     * will return the average of the middle two values.
     * 
     * @param nums the list of values
     * @return the median
     */
    public static int getMedianValue(List<Integer> nums) {
        List<Integer> copy = new ArrayList<Integer>(nums);
        Collections.sort(copy);

        int numberOfValues = copy.size();
        if (numberOfValues % 2 == 0) {
            // we have an even number of values
            // example: for 6 values, we want to return the average of indices 2 and 3
            // (0, 1, 2, 3, 4, 5)
            int val1 = copy.get(numberOfValues / 2);
            int val2 = copy.get((numberOfValues - 2) / 2);
            return (val1 + val2) / 2;
        } else {
            // we have an odd number of values
            // example: for 5 values, we want to return the number at index 2 (0, 1, 2, 3, 4)
            return copy.get((numberOfValues - 1) / 2);
        }
    }
}

Related

  1. getGeneMedian(final List doubleArray)
  2. getMedian(Collection list)
  3. getMedian(List list)
  4. getMedian(List numbers)
  5. getMedian(List results)
  6. median(ArrayList values)
  7. median(final List array)
  8. median(List data)
  9. median(List list)