Java中的通用合并排序算法-错误

时间:2018-08-15 12:30:28

标签: java arraylist

有人可以看到此代码有问题吗?我真的找不到错误。在我看来还不错。我正在使用ArrayList创建通用合并排序算法。没有语法错误。

这是我的合并排序代码:

public static <T extends Comparable<T>> void MergeSortArrayList(ArrayList<T> arr){
    ArrayList<T> tmp = new ArrayList<T>();
    int high = arr.size()-1;
    int low = 0;
    sort(arr, tmp, low, high);      
}

private static <T extends Comparable<T>> void sort(ArrayList <T> arr, ArrayList <T> tmp, int low, int high){
    if(low>=high) return;
    int mid = (low+high)/2;
    sort(arr, tmp, low,mid);
    sort(arr, tmp, mid+1,high);
    merge(arr,tmp,low,mid,high);    
}

private static <T extends Comparable<T>> void merge(ArrayList <T> arr, ArrayList <T> tmp, int low, int mid, int high){
    int ml = low;
    int mr = mid+1;
    int i = low;
    int j = low;

    while(ml <= mid && mr <= high){
        if(arr.get(ml).compareTo(arr.get(mr)) < 0){
            tmp.set(i+1, arr.get(ml+1));
        }
        else{
            tmp.set(i+1, arr.get(mr + 1));
        }
    }

    while(ml <= mid){
        tmp.set(i+1, arr.get(ml+1));
    }

    while(mr <= high){
        tmp.set(i+1, arr.get(mr + 1));
    }

    while(j <= high){
        arr.set(j, tmp.get(j));
        j++;
    }
}

根据输出屏幕的显示,我可以看到错误所在的行,但是,经过这么多小时,我真的很疲惫,但仍然无法到达任何地方。任何帮助将不胜感激。

这是输出:

run:
Before sorting: 

String: 
[C, D, A, R, S, O]

Integers: 
[500, 400, 100, 200, 700, 900]

Double: 
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
[500.45, 400.55, 400.54, 100.21, 700.0, 900.99]

Object: 
[olly bula 123, tani lagi 456, adam mate 321, jojo blue 119, lulu hall 300, lola bays 241]
at java.util.ArrayList.rangeCheck(ArrayList.java:657)

at java.util.ArrayList.set(ArrayList.java:448)

After sorting: 
at genericsort.MergeSortArrayList.merge(MergeSortArrayList.java:36)
String: 
at genericsort.MergeSortArrayList.sort(MergeSortArrayList.java:25)
at genericsort.MergeSortArrayList.sort(MergeSortArrayList.java:23)
at genericsort.MergeSortArrayList.sort(MergeSortArrayList.java:23)
at 
genericsort.MergeSortArrayList.MergeSortArrayList(MergeSortArrayList.java:17)
at genericsort.MergeSortArrayList.main(MergeSortArrayList.java:130)
C:\Users\Fiji\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

0 个答案:

没有答案