在这个程序中,任务是重新排列单词数组中给定的字符串以按长度排序,然后使用基数排序方法按字母顺序排序。例如,给定输入:
“bar”,“cat”,“apple”,“bug”,“cog”,“caper”,“antler”,“ankle”,“bear”
正确的输出应该是:bar bug cat cog bear ankle apple caper antler
到目前为止,我给出的目前代码是:bar bug cat cog bear ankle antler caper apple
我的基数排序算法究竟在哪里出错了?为什么“鹿茸”,长度最大的字符串不在输出的末尾?
这是我目前的代码:
import java.util.ArrayList;
public class RadixSort
{
public static void main(String[] args)
{
String[] words = {"bar", "cat", "apple", "bug", "cog", "caper", "antler", "ankle", "bear"};
System.out.print("Before Radix Sort: ");
for (String h : words)
System.out.print(h + " ");
strRadixSort(words);
System.out.print("\n\nAfter Radix Sort: ");
for (String h : words)
System.out.print(h + " ");
System.out.print("\n\nWhat the output should look like: ");
System.out.print("bar bug cat cog bear ankle apple caper antler");
}
public static void strRadixSort(String[] words)
{
ArrayList<String>[] Letterbuckets = new ArrayList[26];
for (int i = 0; i < Letterbuckets.length; i++)
{
Letterbuckets[i] = new ArrayList<String>();
}
boolean exit = false;
int index = 1;
int x = 0;
while (exit == false)
{
exit = true;
for (String i : words)
{
int curIndex= i.length() - index; //start at the last char in string i
if(curIndex < 0)
{
break; //We are done evaluating this word, go to the next word
}
x = determineLetterBucket(i, curIndex);
Letterbuckets[x].add(i);
x = 0;
if (exit == true && curIndex > 0)
{
exit = false;
}
}
//Rearranges the order of the words in the
//word array and clears all letter buckets
//to prepare for the next pass.
int a = 0;
for(int k = 0; k < 26; k++)
{
for (String i : Letterbuckets[k])
{
words[a++] = i;
}
Letterbuckets[k].clear();
}
//Moves to the next least significant letter
index += 1;
}
}
//Determines which number bucket the letter should go into
//e.g. In the string "abc" the char at index 2 is "c",
//therefore this would mean this word would go into bucket 2
//which can also be represented as the "c" bucket.
public static int determineLetterBucket(String currentWord, int currentIndex)
{
int bucket = 0;
int j = 0;
for(int k = 97; k < 123; k++)
{
if(currentWord.charAt(currentIndex) == k)
bucket = j;
else
j++;
}
return bucket;
}
}