Here you can find the source of median(List
Parameter | Description |
---|---|
a | list of doubles. |
public static Double median(List<Integer> list)
//package com.java2s; /*// w w w.j a v a 2 s. co m * LICENSE to be determined */ import java.util.*; public class Main { /** * @param a list of doubles. * @return the median of the list. */ public static Double median(List<Integer> list) { Random r = new Random(list.size()); if (0 == (list.size() % 2)) { // even length return (medianHelper(list, list.size() / 2, r) + medianHelper(list, list.size() / 2 + 1, r)) / 2.0; } else { return (double) medianHelper(list, list.size() / 2 + 1, r); } } private static Integer medianHelper(List<Integer> list, int k, Random r) { Integer pivot; int numPivots = 0; List<Integer> less, greater; ListIterator<Integer> iter; if (list.size() == 1) { return list.get(0); } less = new LinkedList<Integer>(); greater = new LinkedList<Integer>(); pivot = list.get(r.nextInt(list.size())); iter = list.listIterator(); while (iter.hasNext()) { Integer d = iter.next(); if (d < pivot) { less.add(d); } else if (pivot < d) { greater.add(d); } else { numPivots++; } } //System.err.println("size=" + list.size() + "\tk=" + k +"\tpivot=" + pivot + "\tless=" + less.size() + "\tnumPivots=" + numPivots + "\tgreater=" + greater.size()); if (k <= less.size()) { return medianHelper(less, k, r); } else if (k <= less.size() + numPivots) { return pivot; } else { return medianHelper(greater, k - less.size() - numPivots, r); } } }