我現在正在進行計數排序的基數排序。我想我已經在很大程度上理解和遵循的僞代碼,但我得到一個數組越界錯誤:基數排序和計數排序
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at RunRadixSort.radixSort(RunRadixSort.java:47)
at RunRadixSort.main(RunRadixSort.java:15)
我的代碼
import java.text.DecimalFormat;
import java.util.Arrays;
import java.text.DecimalFormat;
import java.util.Arrays;
public class RunRadixSort {
public static void main(String[] args) {
int[] sortNumbers = {4,5,6,2,3,7,2,1,23,5,13};
int[] sorted = new int[sortNumbers.length];
DecimalFormat df = new DecimalFormat("#.########");
int max = getMax(sortNumbers);
long timeStart = System.nanoTime();
sorted = radixSort(sortNumbers, max);
long timeEnd = System.nanoTime();
long elapsedTime = timeEnd - timeStart;
double time = (double)elapsedTime/1000000;
System.out.println(Arrays.toString(sorted));
System.out.println("\nTotal Execution Time: " + df.format(time)+ " miliseconds");
}
public static int getMax(int[] A){
int max = A[0];
for(int i = 1; i < A.length; i++){
if(A[i] > max){
max = A[i];
}
}
return max;
}
public static int[] radixSort(int[] A, int d){
int[] B = new int[A.length];
int[] C = new int[d + 1];
for(int i = 0; i < d; i++){
for(int k = 0; k < A.length; k++){
C[A[k]]++;
}
int total = 0;
for(int l = 0; l < d; l++){
int temp = C[l];
C[l] = total;
total += temp;
}
for(int m = 0; m < A.length; m++){
B[C[A[m]]] = A[m];
C[A[m]]++;
}
}
return B;
}
}
好吧然後我回到了上面發佈的超出界限的錯誤。 – shinjuo 2013-02-28 20:56:17
哪條線是47? – 2013-02-28 21:11:27
對不起,它在這裏 for(int m = 0; m
shinjuo
2013-02-28 21:16:39