tags:

views:

54

answers:

1

I have the following code:

public class LSD{
    public static int R=1<<8;
    public static int bytesword=4;
    public static void radixLSD(int a[],int l,int r){
        int  aux[]=new int[a.length];

        for (int d=bytesword-1;d>=0;d--){
            int i, j;
            int count[]=new int[R+1];
            for ( j=0;j<R;j++) count[j]=0;
            for (i=l;i<=r;i++)
                count[digit(a[i],d)+1]++;
            for (j=1;j<R;j++)
                count[j]+=count[j-1];
            for (i=l;i<=r;i++)
                aux[count[digit(a[i],d)]++]=a[i];
            for (i=l;i<=r;i++)
                a[i]=aux[i-1]; // <-- Line 19
        }
    }

    public static void main(String[]args){
        int a[]=new int[]{3,6,5,7,4,8,9};
        radixLSD(a,0,a.length-1);

        for (int i=0;i<a.length;i++){
            System.out.println(a[i]);
        }
    }

    public static int digit(int n,int d){
        return (n>>d)&1;
    }
}

At runtime it throws the following exception:

java.lang.ArrayIndexOutOfBoundsException: -1
 at LSD.radixLSD(LSD.java:19)
 at LSD.main(LSD.java:29)

Why is that happening?

+1  A: 

I don't know enough about radix sort to know what your code should be, but why it's currently failing is pretty clear. You're calling radixLSD and passing 0 for l:

radixLSD(a,0,a.length-1);

When you get to this code:

for (i=l;i<=r;i++)
    a[i]=aux[i-1];

In the first pass, i is set to l (0), and you try to do aux[i-1], or aux[-1], which is out of bounds

Michael Mrozek
@Michael Mrozek thanks but i think in code something is wrong i have write this code from algorithms in C++ robert sedgewick can anybody give me link where this code is written in more elegant way?