为什么'计算'的价值?不保持不同的递归?

时间:2016-05-11 13:06:34

标签: java recursion pass-by-reference

这是用于计算数组中的反转的Java代码。

private void findInversions(int begin, int end, Integer count) {
    System.out.println("begin: " + begin + ", end: " + end + ", and count is " + count);
    if (end - begin < 1)
        return;
    int middle = (begin + end) / 2;
    findInversions(begin, middle, count);
    System.out.println("begin: " + begin + ", end: " + end + ", here count is " + count);
    findInversions(middle + 1, end, count);
    mergeAndCount(begin, middle, end, count);
    System.out.println("begin: " + begin + ", end: " + end + ", count now is: " + count);
}



private void mergeAndCount(int begin, int middle, int end, Integer count) {

    int[] result = new int[end - begin + 1];
    int aptr = begin;
    int bptr = middle + 1;
    for (int i = 0; i < result.length; i++) {
        if (aptr <= middle && bptr <= end) {
            if (numbers[aptr] < numbers[bptr]) {
                result[i] = numbers[aptr];
                aptr++;
            }
            else { // numbers[aptr] > numbers[bptr]
                // (a[aptr], b[bptr]) is an inversion here
                count++;
                System.out.println("Found: (" + numbers[aptr] + "," + numbers[bptr] + ") " + count);
                result[i] = numbers[bptr];
                bptr++;
            }
        }
        else if (aptr > middle) {
            result[i] = numbers[bptr];
            bptr++;
        }
        else if (bptr > end) {
            result[i] = numbers[aptr];
            aptr++;
        }

    }

    for (int i = 0; i < result.length; i++) {
        numbers[begin + i] = result[i];
    }

}

反转打印得很好,但count永远不会正确,因为它会在递归调用返回后丢失其值。我已经调试了几次,我看到的是count在递归结束后再次变为0,但我无法找到原因。谁能解释一下?

2 个答案:

答案 0 :(得分:2)

require_once __DIR__.'/../app/AppKernel.php';是一个不可变的类。执行Integer时,该值会自动取消装箱到count++,此int会递增,结果会分配到int。但是,您不会修改填充到方法中的实例。你可以。 G。使用count实例,并使用AtomicIntegerincrementAndGet()方法。

答案 1 :(得分:1)

您的mergeAndCount()方法应该返回获得的计数。调用这些方法的方法应该使用返回值。我把它保持为整数,但没有必要;您可以使用原语int

private Integer findInversions(int begin, int end, Integer count) {
    // ... do all your stuff here but change recursive calls:
    count += findInversions(begin, end, count);
    count += mergeAndCount(begin, middle, end, count0;
    // and return what you find
    return count;
}

private Integer mergeAndCount(int begin, int middle, int end, Integer count) {
    // ... do all your stuff here
    return count;
}

你的另一种选择,因为numbers显然是你的计数类中的一个字段,就是将count作为一个字段留在课堂上。这与你所寻求的效果相同。