简体   繁体   English

合并排序-我的代码有什么问题?

[英]Merge Sort - What is wrong with my code?

I am having problems with my merge sort code. 我的合并排序代码有问题。 Each time I run it I encounter a problem with a IndexOutOfBounds Exception, but I can't seem to figure out why... this is the code produced by our professor (who has been known to make mistakes)... anyone spot the problem 每次运行它时,我都会遇到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];
    }
}

Reading your code, its seems that the last variable is used as an index in your code. 读取代码后,似乎last变量被用作代码中的索引。

That's why you can't pass it as a size to your mergeSort method, you have to pass array.length - 1 . 这就是为什么不能将其作为大小传递给mergeSort方法的原因,而必须传递array.length - 1

  • array.length is the size of the array array.length是数组的大小
  • array.length - 1 is the last index of the array array.length - 1是数组的最后一个索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM