0

好的...我正在尝试实现我自己的 bin 排序版本,通常称为桶排序。我运行程序,我得到一个 indexOutOfBounds 错误。我不知道为什么。有人可以解释为什么。请注意,binsort 算法没有完成。int n 是数组的长度,m 是随机数生成器生成的列表的上限,范围为 0 到 100。

public static void binSort (int []array, int n, int m)
{
//create upperbounds
int x = m / 3;                    //33
int y = n - x;                    //67
int z = n;                        //100

int []temp1 = new int [n-1];
int []temp2 = new int [n-1];
int []temp3 = new int [n-1];

for (int i: array)
{
    if(array[i] < x)
    {
        temp1[i] = array[i];
    }
    else if(array[i] < y)
    {
        temp2[i] = array[i];
    }
    else
    {
        temp3[i] = array[i];     
    }
}

for ( int j = 0; j <= x; j++)
    array[j] = temp1[j];
for ( int k = x + 1; k <= y; k++)
    array[k] = temp2[k];
for ( int l = y + 1; l <= z; l++)
    array[l] = temp3[l];

}
4

3 回答 3

5

enhanced for那里有轻微的循环滥用。

for (int i: array)

这里,i不是索引,而是 的一个元素array。每次for迭代时,它都会自动为您执行此操作:

for(int index = 0; index < array.length; index++) {
    int i= array[index];

长话短说,for为你处理迭代,你只需要使用i元素。

于 2012-10-09T17:38:50.377 回答
2

-第一个错误

  for (int i: array)

在上述for-each循环中,在每次迭代中,数组的连续索引值进入 i。所以 i 是值 Not index。

所以 array[i] 是错误的。

使用这样的东西...

for(int index = 0; index < array.length; index++) {
    int i= array[index]

-其次我认为for ( int j = 0; j <= x; j++)应该是j < x

于 2012-10-09T17:40:43.880 回答
0

temp3[]有大小n-1。这意味着最后一个元素将位于 index n-2。因为z = n,这将与 相同temp3[z-2]。但是,在您的最后一个 for 循环l中将达到 value z,这意味着temp3[l]将引发 IndexOutOfBounds 异常。

 int z = n;                        //100
 int []temp3 = new int [n-1];      //last element of temp3 will be at tempt3[z-2]
 for ( int l = y + 1; l <= z; l++) //l will iterate from y + 1 to z
   array[l] = temp3[l];     // temp3[l] will throw indexOutOfBounds when z>=l>z-2

编辑:另外,正如其他人已经指出的那样,for (int i: array)可能不会做你认为它做的事情......

于 2012-10-09T17:44:25.673 回答