我正在编写自己的基数排序方法,用于对字符串中的单词进行排序(例如“the big black cat sat on the beautiful brown mat”将按照“beautiful big black brown cat mat on sat the the”的顺序排序)。该方法接受一个列表(我的自定义列表接口)作为参数,并直接在原地重新排列该列表。
以下是我目前的方法:
public static void stringRadixSort(List<String> list, int letters) {
List<String>[] buckets = (List<String>[]) Array.newInstance(List.class, 26);
int letterNumber = 1; //Sorts list by 1st letter of each word, then 2nd etc.
for (int i = 0; i < letters; i++) {
while (!list.isEmpty()) {
String word = list.remove(list.first());
if (word.length() > letters) throw new UnsortableException("The list contains a word that holds more letters than the given maximum number of letters."
+ "\nMax Letters: " + letters + "\nWord: " + word);
String letter = word.substring(letterNumber - 1, letterNumber); //EXCEPTION THROWN
char ch = letter.charAt(0);
int index = ch - 'a'; //gets index of each letter ('a' = buckets[0], 'z' = buckets[25]
if (buckets[index] == null) {
buckets[index] = new LinkedList<String>();
}
buckets[index].insertLast(word);
}
for (int j = 0; j < buckets.length; j++) {
if (buckets[j] != null) {
while (!buckets[j].isEmpty()) {
list.insertLast(buckets[j].remove(buckets[j].first()));
}
}
}
letterNumber++;
}
}
我的方法(也希望是唯一的问题)是在读取单词的每个字符时,创建一个单个字母的子字符串。由于外部的“for”循环运行了“letters”次(其中“letters”是List中最长单词的长度),因此当这个循环迭代大于当前单词的长度时 - 即“letterNumber > word.length()” - 就会抛出异常,因此它试图使用大于字符串长度的String索引创建子字符串。
我应该如何调整我的方法,使其仅在“letterNumber == word.length()”之前创建每个单词的子字符串,并能将排序算法应用于这些较短的单词 - “a”将变成“aa”的前面。