我为最重要的基数排序编写了代码但是我一直在行上得到IndexBoundsException的错误:arr [i] = arr1.get(i);.现在我不知道什么是错的,因为逻辑似乎对我来说。
public static int[] msdRadixSort(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("The array is null!");
}
//search through to find msd
int temp = arr[0];
for (int i = 0; i < arr.length; i++) {
if (Math.abs(temp) <= Math.abs(arr[i])) {
temp = arr[i];
}
}
//find the length of the msd
int k = 1;
while (!(temp / 10 == 0)) {
temp = temp / 10;
k++;
}
ArrayList<Integer> arr1 = new ArrayList<Integer>(arr.length);
for (int i = 0; i < arr.length; i++) {
arr1.add(arr[i]);
}
msdRadixSort(arr1, k);
System.out.println(arr1);
for (int i = 0; i < arr.length; i++) {
arr[i] = arr1.get(i);
}
return arr;
}
答案 0 :(得分:1)
嵌套循环不正确应该是
for (int j = 0; j < bucket.length; j++) {
for (int i = 0; i < bucket[j].size(); i++) {
arr.add(bucket[j].get(i));
}
}