我正在尝试制作Radix排序算法,并且我有一个数组列表的数组列表 .
基数排序将元素添加到“外部”数组列表,具体取决于数字的值,数字,数字,数百等等 . 每个“内部”数组列表对应于0,1,2,3 ... 9的数字位置 .
变量“base”的值为10,因为有10位数(0-9)
这是宣言:
ArrayList<ArrayList<Integer>> digits = new ArrayList<ArrayList<Integer>>(base); //arraylist that can hold 10 elements to sort elements according to digits 0-9
for(int i=0; i <digits.size(); i++){
digits.add(i, new ArrayList<Integer>()); //make an arraylist for each element inside the digits array list, this will hold the numbers that are being sorted
}
但是,稍后当我尝试将整数添加到正确的“内部”数组列表中时,我无法正在尝试将整数添加到ArrayList类型的位置 . 我也得到一个索引超出范围的错误 .
while(!(lastDigit)) //if last digit has not been reached
{
lastDigit = true;
for(int k=0; k < array.length; k++) //array contains the numbers we are sorting
{
number = k / digitPlace; //digitPlace starts off as 1 to first sort by one's place and is then later multiplied by 10
int index = number % base; //get digit from correct place
digits.add(index, k);//line with the ERROR; add the element in the correct place (according to it's digit)
if(number > 0 && lastDigit)
{
lastDigit = false;
}
}
解决问题的方法是我将整数转换为类型ArrayList,但这意味着我会在内部数组列表中添加一个数组列表,这不是我想要的 . 我想在正确的“内部”ArrayList中添加一个int .
2 回答
JavaDoc of size():
您正在引用for循环中列表的 size 而不是 capacity !
使用用于创建List的基本变量而不是digits.size()
digits.get(index).add(n);
其中
n
是要添加的输入数组的编号 .