Returns the median of a vector. - Java java.lang

Java examples for java.lang:Math Matrix

Description

Returns the median of a vector.

Demo Code


//package com.java2s;

public class Main {
    /**//from w w  w .j a v  a  2  s. c o  m
     * Returns the median of a vector.
     */
    public static double getMedianThreshold(double[] input) {
        int low = 0;
        int high = input.length - 1;
        int median = (low + high) / 2;
        int middle, ll, hh;

        while (true) {
            if (high <= low) /* One element only */
                return input[median];

            if (high == low + 1) { /* Two elements only */
                if (input[low] > input[high]) {
                    double t = input[low];
                    input[low] = input[high];
                    input[high] = t;
                }
                return input[median];
            }

            /* Find median of low, middle and high items; swap into position low */
            middle = (low + high) / 2;
            if (input[middle] > input[high]) {
                double t = input[middle];
                input[middle] = input[high];
                input[high] = t;
            }
            if (input[low] > input[high]) {
                double t = input[low];
                input[low] = input[high];
                input[high] = t;
            }
            if (input[middle] > input[low]) {
                double t = input[middle];
                input[middle] = input[low];
                input[low] = t;
            }

            /* Swap low item (now in position middle) into position (low+1) */
            double t = input[middle];
            input[middle] = input[low + 1];
            input[low + 1] = t;

            /* Nibble from each end towards middle, swapping items when stuck */
            ll = low + 1;
            hh = high;
            while (true) {
                do
                    ll++;
                while (input[low] > input[ll]);
                do
                    hh--;
                while (input[hh] > input[low]);

                if (hh < ll)
                    break;

                // swap
                t = input[ll];
                input[ll] = input[hh];
                input[hh] = t;
            }

            /* Swap middle item (in position low) back into correct position */
            t = input[low];
            input[low] = input[hh];
            input[hh] = t;

            /* Re-set active partition */
            if (hh <= median)
                low = ll;
            if (hh >= median)
                high = hh - 1;
        }
    }
}

Related Tutorials