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);
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 theenqueuemethod onnull. You need to loop through each position of the array and assign it anew Queue()or however you initialize those.So for example: