mergesort

rbl8hiat  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(278)

我正在浏览下面的示例程序,试图理解下面的递归是如何工作的,我无法理解左数组元素和右数组元素是如何排序的,最后合并了两个子数组,如下所示。以下方法的任何图示解释都会有很大帮助,因为我试图理解下面的递归代码。

public static int[] mergeSort(int[] arrayToSort) {

    // BASE CASE: arrays with fewer than 2 elements are sorted
    if (arrayToSort.length < 2) {
        return arrayToSort;
    }

    // STEP 1: divide the array in half
    // we use integer division, so we'll never get a "half index"
    int midIndex = arrayToSort.length / 2;

    int[] left  = Arrays.copyOfRange(arrayToSort, 0, midIndex);
    int[] right = Arrays.copyOfRange(arrayToSort, midIndex, arrayToSort.length);

    // STEP 2: sort each half
    int[] sortedLeft  = mergeSort(left);
    int[] sortedRight = mergeSort(right);

    // STEP 3: merge the sorted halves
    int[] sortedArray = new int[arrayToSort.length];

    int currentLeftIndex  = 0;
    int currentRightIndex = 0;

    for (int currentSortedIndex = 0; currentSortedIndex < arrayToSort.length;
            currentSortedIndex++) {

        // sortedLeft's first element comes next
        // if it's less than sortedRight's first
        // element or if sortedRight is exhausted
        if (currentLeftIndex < sortedLeft.length
                && (currentRightIndex >= sortedRight.length
                || sortedLeft[currentLeftIndex] < sortedRight[currentRightIndex])) {
            sortedArray[currentSortedIndex] = sortedLeft[currentLeftIndex];
            currentLeftIndex++;
        } else {
            sortedArray[currentSortedIndex] = sortedRight[currentRightIndex];
            currentRightIndex++;
        }
    }

    return sortedArray;
}
fbcarpbf

fbcarpbf1#

排序在合并循环中执行:
如果数组非常小(0或1个元素), mergeSort() 立即归还。
否则,它会将阵列分成两个大小大致相同的子阵列, left 以及 right ,通过递归调用相同的方法进行排序:

// STEP 2: sort each half
  int[] sortedLeft  = mergeSort(left);
  int[] sortedRight = mergeSort(right);

最后一步遍历已排序的半部分以生成新的已排序数组。
递归调用之所以完成,是因为它们只使用严格小于参数数组的子数组执行。

相关问题