MergeSort - ArrayIndexOutOfBoundsException

时间:2014-04-07 00:15:45

标签: java sorting merge indexoutofboundsexception mergesort

我很抱歉,如果已经在某个地方得到了解答,我花了一个多小时搜索了之前的许多问题,但没有一个能够帮助我解决这个错误。

我随机收到一个错误,可能是70%的时间:

--------------------Configuration: MergeSort - JDK version 1.7.0_45 <Default> - <Default>-    -------------------

Random array: 17 14 3 4 1 10 13 9 3 1 6 9 10 2 17 8 10 5 7 8 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20

at MergeSort.merge(MergeSort.java:64)
at MergeSort.mergeSort(MergeSort.java:26)
at Driver.main(Driver.java:18)

Process completed.

第64行将引用:&#34; scratch [scratch_index] = list [i];&#34;

public void merge(int[] list, int first, int middle, int last)
{
    int[] scratch = new int[list.length];

    int midpoint = (first+last)/2;

    int left_index = first;
    int right_index = middle + 1;
    int scratch_index = left_index;

    while((left_index <= midpoint) && (right_index <= last))
    {
        if(list[left_index] <= list[right_index])
        {
            scratch[scratch_index] = list[left_index];
            left_index +=1;
        }
        else
        {
            scratch[scratch_index] = list[right_index];
            right_index +=1;
        }
        scratch_index +=1;
    }

    for(int i=left_index;i<=midpoint;i++)
    {
        scratch[scratch_index] = list[i];
        scratch_index +=1;
    }
    for(int i=right_index;right_index<=last;i++) // I am line 64
    {
        scratch[scratch_index] = list[i];
        scratch_index +=1;
    }
    for(int i=0;i<list.length;i++)
    {
        list[i] = scratch[i];
    }
}

这是我在本网站上的第一个问题,对不起,如果我没有正确格式化这个问题,我们非常感谢您的建议。

如果需要任何其他信息来帮助我解决此错误,请告诉我们。 谢谢!

2 个答案:

答案 0 :(得分:0)

索引使用“从零开始编号”&gt;&gt; https://en.wikipedia.org/wiki/Zero-based_numbering

String example = "01234";
System.out.println(example.size()); //Prints out 5
System.out.println(exmaple.indexOf("1")); //Prints out 1

您的for语句需要检查最后一个索引

for(int i=right_index;right_index<last;i++)

或(不推荐)

for(int i=right_index;right_index<=last-1;i++) //Works, but not recommended due to conventions


//index       0  1  2 3 4 5  6  7 8 9 10 11 12 13 14 15 16 17 18 19
Random array: 17 14 3 4 1 10 13 9 3 1 6  9  10 2  17 8  10 5  7  8 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20

答案 1 :(得分:0)

在评论// I am line 64您正在递增i而不是right_index,这将导致索引继续增加,直到达到索引超出范围,因此替换它,

for(int i=right_index;right_index<=last;i++) // I am line 64

由此:

for(int i=right_index; i<=last;i++)