java合并排序算法中的递归方法

时间:2015-05-06 02:15:57

标签: java algorithm

我的应用程序中有以下合并排序代码。我很困惑如果在不满足if条件时if块出来之后再次调用递归方法。我调试了我的代码,但我仍然没有得到它。调用mergesort(0,number - 1)的sort方法首先在mergesort(0,5)处开始。 low低于high,middle为2,所以mergesort(0,2)接下来运行。这一直持续到我们有mergesort(0,0),在这种情况下low不低于 所以它来自if块。但是当我调试时,该方法返回,并在mergesort(0,0)case之后再次启动。电话如何再次发生? 请帮我。感谢您抽出宝贵时间阅读我的问题:)

    public class MergeSort {
        private int[] numbers;
        private int[] helper;

    private int number;


    public int[] sort(int[] values) {
        this.numbers = values;
        number = values.length;
        this.helper = new int[number];
        return mergesort(0, number - 1);
    }

    private int[] mergesort(int low, int high) {
        // check if low is smaller then high, if not then the array is sorted
        if (low < high) {
            // Get the index of the element which is in the middle
            int middle = low + (high - low) / 2;
            // Sort the left side of the array
            mergesort(low, middle);
            // Sort the right side of the array
            mergesort(middle + 1, high);
            // Combine them both
            merge(low, middle, high);
        }
        return numbers;
    }

    private int[] merge(int low, int middle, int high) {

        // Copy both parts into the helper array
        for (int i = low; i <= high; i++) {
            helper[i] = numbers[i];
        }

        int i = low;
        int j = middle + 1;
        int k = low;
        // Copy the smallest values from either the left or the right side back
        // to the original array
        while (i <= middle && j <= high) {
            if (helper[i] <= helper[j]) {
                numbers[k] = helper[i];
                i++;
            } else {
                numbers[k] = helper[j];
                j++;
            }
            k++;
        }
        // Copy the rest of the left side of the array into the target array
        while (i <= middle) {
            numbers[k] = helper[i];
            k++;
            i++;
        }
        return numbers;

    }
}

1 个答案:

答案 0 :(得分:2)

这是因为mergesort方法调用自身两次。您可以打印出堆栈以查看会发生什么。

例如,在致电mergesort(0,1)时,该方法会先调用mergesort(0,0),然后调用mergesort(1,1)