Here you can find the source of medianHelper(List
private static Integer medianHelper(List<Integer> list, int k, Random r)
//package com.java2s; /*//from w w w .j ava2 s.c o m * LICENSE to be determined */ import java.util.*; public class Main { 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); } } }