好的,所以我试图在Java中实现合并排序,但是在数组拆分时遇到了以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: 2 > 1
    at java.util.Arrays.copyOfRange(Arrays.java:3591)
    at MergeSortS.recMergeSort(MergeSortS.java:26)
    at MergeSortS.recMergeSort(MergeSortS.java:28)
    at MergeSortS.mergeSort(MergeSortS.java:17)
    at MergeSortM.main(MergeSortM.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)


我的代码段如下,请帮助我在此处确定我的问题... :(
我特意在最后注释掉了recMergeSort(right)递归调用,因为我想更正recMergeSort(left)调用...

public void recMergeSort(int[] tempArray){
        if(tempArray.length>1){
            int mid=(tempArray.length)/2;

            int[] left=Arrays.copyOfRange(tempArray,0,mid);

            int[] right=Arrays.copyOfRange(tempArray,mid+1,tempArray.length-1);

            recMergeSort(left);
            //recMergeSort(array, right, mid+1, right.length-1);
        }
    }


编辑
好的,所以我检查了另一个站点和copyOfRange方法上的javadoc,要求满足以下条件:

Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)


修复后,如下所示:

public void recMergeSort(int[] tempArray){
        if(tempArray.length>1){
            int mid=(tempArray.length)/2;

            int[] left=Arrays.copyOfRange(tempArray,0,mid+1);

            int[] right=Arrays.copyOfRange(tempArray,mid+1,tempArray.length);

            recMergeSort(left);
            //recMergeSort(array, right, mid+1, right.length-1);
        }
    }


我收到以下错误:

Exception in thread "main" java.lang.StackOverflowError


请帮助我纠正此问题... :(

最佳答案

看来您被Arrays.copyOfRange()方法所困扰。请尝试以下代码:

public void recMergeSort(int[] tempArray){
    if (tempArray.length > 1 ){
        int mid=(tempArray.length)/2;                                       // mid = 2
        int[] left = Arrays.copyOfRange(tempArray, 0, mid);                 // [10, 20]
        int[] right = Arrays.copyOfRange(tempArray, mid, tempArray.length); // [30, 40, 50]

        recMergeSort(left);
        //recMergeSort(array, right, mid+1, right.length-1);
    }
}


Arrays.copyOfRange(array, lowIndex, highIndex)将复制从lowIndex包含项和highIndex排除项进行的访问。这意味着左副本的highIndex应该与右副本的lowIndex相同。

用法:

int[] tempArray = new int[] {10, 20, 30, 40, 50};
recMergeSory(tempArray);

10-04 12:29