Here you can find the source of getMedianValue(List
Parameter | Description |
---|---|
nums | the list of values |
public static int getMedianValue(List<Integer> nums)
//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); } } }