I would love a code review of this LSD radix sort implementation. I've rolled my own, and have implemented counting sort as well. I feel like some of the data structures I've chosen could be improved. My List<List<char[]>>
, for instance, is a little gross and makes fiddling with its innards more complex than I think needs to be.
public class LSDSorting {
private static final int DIGIT_RANGE = 5;
public static void main(String[] args) {
char[][] toSort = new char[][]{"0123".toCharArray(), "1233".toCharArray(), "1212".toCharArray(), "1111".toCharArray(), "4444".toCharArray()};
int LSD_INDEX = toSort[0].length - 1;
char[][] sorted = lsdSort(toSort, LSD_INDEX);
for (char[] str: sorted) {
System.out.println(String.valueOf(str));
}
}
private static char[][] lsdSort(char[][] toSort, int d) {
if (d < 0) {
return toSort;
}
char[][] sortedOnD = runCountingSort(d, toSort, DIGIT_RANGE);
return lsdSort(sortedOnD, d-1);
}
private static char[][] runCountingSort(int d, char[][] toSort, int range) {
List<List<char[]>> idx = new ArrayList<>();
for (int i = 0; i < range; i++) {
idx.add(i, new ArrayList<char[]>());
}
for (int i = 0; i < toSort.length; i++) {
int currVal = Character.getNumericValue(toSort[i][d]);
List<char[]> currList = idx.get(currVal);
if (currList == null) {
currList = new ArrayList<>();
idx.add(currVal, currList);
}
currList.add(toSort[i]);
}
char[][] result = new char[toSort.length][toSort[0].length];
int currIdx = 0;
for (int i = 0; i < idx.size(); i++) {
for (char[] str : idx.get(i)) {
result[currIdx] = str;
currIdx++;
}
}
return result;
}
}