我的合并排序代码有问题。每次运行它时,我都会遇到 IndexOutOfBounds 异常的问题,但我似乎无法弄清楚为什么......这是我们的教授(已知会犯错误)产生的代码......任何人都发现了问题
public static <T extends Comparable<T>> void mergeSort(T[] array, int first, int last)
{
if(first<last)
{
int mid = (first+last)/2;
mergeSort(array, first, mid);
mergeSort(array, mid+1, last);
merge(array, first, mid, last);
}
}
public static <T extends Comparable<T>> void mergeSort(T[] array, int last)
{
int first = 0;
if(first<last)
{
int mid = (first+last)/2;
mergeSort(array, first, mid);
mergeSort(array, mid+1, last);
merge(array, first, mid, last);
}
}
public static <T extends Comparable<T>> void merge(T[] array, int first, int mid, int last)
{
int maxSize = array.length;
T[] tempA = (T[]) new Comparable[maxSize];
int first1 = first;
int last1 = mid;
int first2 = mid+1;
int last2 = last;
int index = first1;
while((first1<=last1) && (first2<=last2))
{
if(array[first1].compareTo(array[first2])<0)
{
tempA[index] = array[first1];
first1++;
}
else
{
tempA[index] = array[first2];
first2++;
}
index++;
}
while(first1<=last1)
{
tempA[index]=array[first1];
first1++;
index++;
}
while(first2<=last2)
{
tempA[index]=array[first2];
first2++;
index++;
}
for(index=first; index<=last;++index)
{
array[index]=tempA[index];
}
}