【问题标题】:Finding the median value of a random array [duplicate]查找随机数组的中值[重复]
【发布时间】:2012-07-21 22:49:27
【问题描述】:

可能重复:
Finding the median value of an array?
How to calculate mean, median, mode and range from a set of numbers
Combine QuickSort and Median selection algorithm

如何找到随机生成的数组的中值?

例如:它会给我一个像 88,23,93,65,22,43 这样的数组。 我使用的代码找到了中间的数字,但它没有排序。

这是我目前使用的代码:

double Median()
{
    int Middle = TheArrayAssingment.length / 2;
       if (TheArrayAssingment.length%2 == 1)
        {
           return TheArrayAssingment[Middle];
        }
    else {
        return (TheArrayAssingment[Middle-1] + TheArrayAssingment[Middle]) / 2.0;
    }
}

【问题讨论】:

标签: java median


【解决方案1】:

您的代码看起来不错,但 它假定数组已排序。 只需对其进行排序:

Arrays.sort(TheArrayAssignment);

【讨论】:

    【解决方案2】:
    public static double median(int[] a) {
        int[] b = new int[a.length];
        System.arraycopy(a, 0, b, 0, b.length);
        Arrays.sort(b);
    
        if (a.length % 2 = 0) {
            return (b[(b.length / 2) - 1] + b[b.length / 2]) / 2.0;
        } else {
            return b[b.length / 2];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 2017-09-15
      • 2021-12-26
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      相关资源
      最近更新 更多