Java Random medianHelper(List list, int k, Random r)

Here you can find the source of medianHelper(List list, int k, Random r)

Description

median Helper

License

Open Source License

Declaration

private static Integer medianHelper(List<Integer> list, int k, Random r) 

Method Source Code


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

Related

  1. getRandomPort(int low, int high)
  2. getRandomRequestId(Integer serviceId)
  3. getRandomServices(int maxSize)
  4. getRandomUUID()
  5. isRandomList(List list)
  6. multSample(Random rng, double[] vals, double normsum)
  7. permute(Object[] arr, Random random)
  8. rand()
  9. Rand()