0

我有这个方法来获得中值,

public double getMedian(double[] numberList) {
        int factor = numberList.length;
        double[] first = new double[(int) factor / 2];
        double[] last = new double[first.length];
        double[] middleNumbers = new double[1];
        for (int i = 0; i < first.length; i++) {
            first[i] = numberList[i];
        }
        for (int i = numberList.length; i >= last.length; i--) {
            last[i] = numberList[i];
        }
        for (int i = 0; i <= numberList.length; i++) {
            if (numberList[i] != first[i] || numberList[i] != last[i])
                middleNumbers[i] = numberList[i];
        }
        if (numberList.length % 2 == 0) {
            double total = middleNumbers[0] + middleNumbers[1];
            return total / 2;
        } else {
            return middleNumbers[0];
        }
    }

但给我一个IndexOutOfBounds异常。有人可以帮我解决错误吗?

4

2 回答 2

3

您应该使用i < numberList.length,而不是i <= numberList.length;数组的合法索引[0, array.length-1],即array.length不是合法索引

于 2013-04-09T17:31:26.170 回答
2

简化答案
如果您只想要中值,只需使用 if-else on numberList,就不需要任何子数组:

public double getMedian(double[] numberList) {
    int middle = numberList.length / 2;
    if (numberList.length % 2 == 0) {
        double total = numberList[middle - 1] + numberList[middle]
        return total / 2;
    } else {
        return numberList[middle];
    }
}

原始答案
正如我在 Zim-Zam 的回答中所说,这个循环也没有使用正确的索引:

for (int i = numberList.length; i >= last.length; i--) {
    last[i] = numberList[i];
}

last只能0通过numberList.length / 2(向下舍入)。
看起来您想要将两个拆分numberListfirstand last,只需使用:

int[] first = Arrays.copyOfRange(numberList, 0, factor);
int[] last = Arrays.copyOfRange(numberList, factor, numberList.length);

而不是你的 for 循环。

于 2013-04-09T18:00:26.950 回答