wasim
wasim

Reputation: 123

NullPointerException with radix sort

I try to program radix sort, but I have NullPointerException when I run this code

public class ThreeRadixSort {

    public Queue getSortedData(Queue queue){
        Queue array[] = new Queue[10];

        for(int i=1;i<=3;i++){

        while(queue.front != null){
            Student student = queue.dequeue();

            if( i == 1) 
                array[(int)(student.id%10)].enqueue(student);
            else if( i == 2)
                array[(int)((student.id%100)/10)].enqueue(student);
            else    
                array[(int)(student.id/100)].enqueue(student);

        }

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

        while( array[j] != null && array[j].front != null)
            queue.enqueue(array[j].dequeue());
        }
        }   
        return queue;
    }
}

The Exception show when the implement reach to

    array[(int)(student.id%10)].enqueue(student);

Upvotes: 1

Views: 155

Answers (2)

Toad
Toad

Reputation: 15925

this line:

 Queue array[] = new Queue[10]

only declares an array of queues. It does not allocate the queues itself. you should initialize them like this:

 for(int i; i<10; i++)
 {
      array[i] = new Queue();
 }

p.s. by the way. Instead of relying on a magic number like '10' it's better practice to make it a constant and declare on the top of your program. Like such:

 const int numElements = 10;

Upvotes: 1

danben
danben

Reputation: 83250

The problem here is that when you initialize your array of Queue, each spot is initialized to null. So right now, you are trying to call the enqueue method on null. You need to loop through each position of the array and assign it a new Queue() or however you initialize those.

So for example:

for (int i = 0; i < array.length; i++) {
  array[i] = new Queue();
}

Upvotes: 1

Related Questions