2 * Copyright (c) 2003-2005 The BISON Project
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 2 as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 import java.util.ArrayList;
22 import java.util.Collections;
25 * This class adds the ability to retrieve the median element to the
26 * {@link IncrementalStats} class. Note that this class actually stores all
27 * the elements, so (unlike in its superclass) storage requirements depend
28 * on the number of items processed.
32 public class MedianStats extends IncrementalStats
35 /** Structure to store each entry. */
36 private final ArrayList<Double> data=new ArrayList<Double>();
38 /** Calls {@link #reset}. */
45 * Retrieves the median in the current data collection.
47 * @return The current median value.
49 public double getMedian()
54 throw new IllegalStateException("Data vector is empty!");
57 Collections.sort(data);
58 if (data.size() % 2 != 0) { // odd number
59 result = data.get(data.size() / 2);
60 } else { // even number:
61 double a = data.get(data.size() / 2);
62 double b = data.get(data.size() / 2 - 1);
68 public void add(double item, int k)
70 for (int i = 0; i < k; ++i) {
72 data.add(new Double(item));
84 public static void main( String[] args ) {
85 MedianStats s = new MedianStats();
86 for(int i=0; i<args.length; i++) s.add(Double.parseDouble(args[i]));
87 System.out.println("Average: "+s.getAverage());
88 System.out.println("Median: "+s.getMedian());