我现在正在研究实现计数排序的基数排序。我想我在很大程度上理解并遵循了伪代码,但是我得到了一个数组越界错误:
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;
}
}