Search code examples
javacountradix-sort

Radix Sort and count sort


I am now working on radix sort that implements count sort. I think I have for the most part understood and followed the pseudo code, but I am getting an array out of bounds error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
    at RunRadixSort.radixSort(RunRadixSort.java:47)
    at RunRadixSort.main(RunRadixSort.java:15)

My Code

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;
    }
}

Solution

  • You are not incrementing j. This could be a typo:

     for(int j = 0; j < d; i++){
    

    try this:

    for(int j = 0; j < d; j++){