我正在进行“合并排序”,并且正在抛出ArrayIndexOutOfBoundsException。我一直在寻找错误的代码,找不到它。异常堆栈跟踪表明它来自我在77行的temp[current3++] = list2[current2++];合并功能。第102行是merge(firstHalf, secondHalf, list);,第93行是mergeSortRoutine(firstHalf);。任何帮助都将不胜感激。感谢您的时间。

以下是两个功能:

//this function will merge two arrays
private static void merge(Integer[] list1, Integer[] list2, Integer[] temp){
    int current1 = 0; //current index in list1
    int current2 = 0; //current index in list2
    int current3 = 0; //current index in temp

    while((current1 < list1.length) && (current2 < list2.length)){

        if(list1[current1].intValue() < list2[current2].intValue()){
            temp[current3++] = list1[current1++];
        }
        else{
            temp[current3++] = list2[current2++];
        }
    }

    while(current1 < list1.length){
        temp[current3++] = list2[current2++];
    }

    while(current2 < list2.length) {
        temp[current3++] = list2[current2++];
    }
}

//merge sort function
private static void mergeSortRoutine(Integer[] list){

    if(list.length > 1){

        //merge sort the first half
        Integer[] firstHalf = new Integer[(list.length)/2];
        System.arraycopy(list, 0, firstHalf, 0, (list.length)/2);
        mergeSortRoutine(firstHalf);

        //merge sort the second half
        int secondHalfLength = list.length - ((list.length)/2);
        Integer[] secondHalf = new Integer[secondHalfLength];
        System.arraycopy(list, (list.length)/2, secondHalf, 0, secondHalfLength);
        mergeSortRoutine(secondHalf);

        //merge firstHalf with secondHalf into list
        merge(firstHalf, secondHalf, list);
    }
}


下面是堆栈跟踪:

java.lang.ArrayIndexOutOfBoundsException: 1
at Merge.merge(Merge.java:77)
at Merge.mergeSortRoutine(Merge.java:102)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.mergeSortRoutine(Merge.java:93)
at Merge.main(Merge.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

最佳答案

正如Scary Wombat所说,在最后一个while循环中,您要检查current2,然后对其进行递增。

除此之外,还要在倒数第二个current2循环while中增加while(current1 < list1.length)。我认为您可能希望该语句为temp[current3++] = list1[current1++]

08-07 02:39