Here you can find the source of median(long[] array)
Parameter | Description |
---|---|
array | a long array. |
public static double median(long[] array)
//package com.java2s; // it under the terms of the GNU General Public License as published by // public class Main { /**/*from w w w .j a va2s .co m*/ * @param array a long array. * @return the median of the values in this array. */ public static double median(long[] array) { return median(array, array.length); } /** * @param array a double array. * @return the median of the values in this array. */ public static double median(double[] array) { return median(array, array.length); } /** * @param array a long array. * @param N the number of values of array which should be considered. * @return the median of the first N values in this array. */ public static long median(long array[], int N) { long a[] = new long[N + 1]; System.arraycopy(array, 0, a, 0, N); a[N] = Long.MAX_VALUE; long v, t; int i, j, l = 0; int r = N - 1, k1 = r / 2, k2 = r - k1; while (r > l) { v = a[l]; i = l; j = r + 1; for (;;) { while (a[++i] < v) { } while (a[--j] > v) { } if (i >= j) { break; } t = a[i]; a[i] = a[j]; a[j] = t; } t = a[j]; a[j] = a[l]; a[l] = t; if (j <= k1) { l = j + 1; } if (j >= k2) { r = j - 1; } } return (a[k1] + a[k2]) / 2; } /** * @param array a double array. * @param N the number of values of array which should be considered. * @return the median of the first N values in this array. */ public static double median(double array[], int N) { double a[] = new double[N + 1]; System.arraycopy(array, 0, a, 0, N); a[N] = Double.POSITIVE_INFINITY; double v, t; int i, j, l = 0; int r = N - 1, k1 = r / 2, k2 = r - k1; while (r > l) { v = a[l]; i = l; j = r + 1; for (;;) { while (a[++i] < v) { } while (a[--j] > v) { } if (i >= j) { break; } t = a[i]; a[i] = a[j]; a[j] = t; } t = a[j]; a[j] = a[l]; a[l] = t; if (j <= k1) { l = j + 1; } if (j >= k2) { r = j - 1; } } return (a[k1] + a[k2]) / 2; } }