好吧...我正在尝试实现我自己版本的 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];
}
最佳答案
其中存在对增强型
循环的轻微误用。
for (int i: array)
这里,i
不是索引,而是array
的一个元素。每次 for
迭代时,它都会自动为您执行此操作:
for(int index = 0; index < array.length; index++) {
int i= array[index];
长话短说,for
会为您处理迭代,您只需使用 i
元素即可。
关于java - IndexOutOfBoundsException 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12805320/