Java List Median median(List list)

Here you can find the source of median(List list)

Description

median

License

Open Source License

Parameter

Parameter Description
a list of doubles.

Return

the median of the list.

Declaration

public static Double median(List<Integer> list) 

Method Source Code


//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);
        }
    }
}

Related

  1. median(List data)
  2. median(List list)
  3. median(List list)
  4. median(List p)
  5. median(List sortedDataAscendingOrder)
  6. median(List data)
  7. median(List data)
  8. medianAbsVal(List vals)
  9. medianAbsValAboveThresh(List vals, double thresh)