For homework in an algorithms class we had to write a program that implemented a Radix sort algorithm. I ended up implementing it in a round about way, and it functions correctly. However there is a part of my code that is an atrocious looking if else block in a for loop. I have to retrieve the items out of an array of linked lists in the correct order and add the elements back into an Integer array. One of my classmates and I spent quite a while trying to figure out how to put this block into for loops but could just not come up with a to do that. So that's my questions, how would I put the objects of the linked lists in an array into a different array. The code I came up for the sort method is below:
private static Integer[] sort(Integer[] input, int place){
//create an array of linked lists
LinkedList<Integer>[] bucketsOut = new LinkedList[10];
//initialize the linked lists
for(int i=0; i < 10; i++){
bucketsOut[i] = new LinkedList<Integer>();
}
int bucketPlacement = 0;
//place every input into the correct bucket
for(int i = 0; i < input.length; i++){
bucketPlacement = getDigit(input[i].intValue(), place);
bucketsOut[bucketPlacement].add(input[i]);
}
//Place the elements out of the linked lists into the correct place in input[]
for(int i = 0; i < input.length; i++){ //for each input number
if(bucketsOut[0].peekFirst() != null){
input[i] = bucketsOut[0].pollFirst().intValue();
}else if(bucketsOut[1].peekFirst() != null){
input[i] = bucketsOut[1].pollFirst().intValue();
}else if(bucketsOut[2].peekFirst() != null){
input[i] = bucketsOut[2].pollFirst().intValue();
}else if(bucketsOut[3].peekFirst() != null){
input[i] = bucketsOut[3].pollFirst().intValue();
}else if(bucketsOut[4].peekFirst() != null){
input[i] = bucketsOut[4].pollFirst().intValue();
}else if(bucketsOut[5].peekFirst() != null){
input[i] = bucketsOut[5].pollFirst().intValue();
}else if(bucketsOut[6].peekFirst() != null){
input[i] = bucketsOut[6].pollFirst().intValue();
}else if(bucketsOut[7].peekFirst() != null){
input[i] = bucketsOut[7].pollFirst().intValue();
}else if(bucketsOut[8].peekFirst() != null){
input[i] = bucketsOut[8].pollFirst().intValue();
}else if(bucketsOut[9].peekFirst() != null){
input[i] = bucketsOut[9].pollFirst().intValue();
}
}
//return sorted list for digit
return input;
}
elses.) If your environment had aCompositeCollectionlike Apache Commons, you could instantiate one fortoArray()(to be followed by aSystem.arraycopy(), if need be).