【发布时间】:2017-05-03 16:02:00
【问题描述】:
我无法理解基数排序。我应该把单词的最后一个字母从右到左排序,直到没有剩下的字母为止。
文本文件如下所示
酒吧 猫 苹果 漏洞 齿轮 跳跃 鹿茸 踝 承担
我的输出是这样的
脚踝 鹿茸 苹果 酒吧 熊 漏洞 跳跃 猫 齿轮
但我应该得到这样的输出
酒吧 漏洞 猫 齿轮 熊 踝 苹果 跳跃 鹿茸
感觉就像我接近拥有正确的代码,但我被卡住了,不知道还能做什么。如果我能得到帮助并指出正确的方向,将不胜感激
这是我所做的代码
RadixSort.java
public class RadixSort {
public static void main(String[]args) throws FileNotFoundException{
Linkedlist[] allNameLinkedList = new Linkedlist[26]; // create an array
of LinkedList for 26 letters in alphabets
int count = 0;
// initialize all the elements in the array to new LinkedList
for (int i = 0; i < allNameLinkedList.length; i++) {
allNameLinkedList[i] = new Linkedlist();
}
Scanner scan = new Scanner(new File("words.txt"));
while(scan.hasNextLine())
{
String currentname = scan.nextLine();
for(int i = 0; i < 26; i++){
if(currentname.charAt(2) == (char)(i+97))
{
allNameLinkedList[i].addNodeToTheEndOfTheList(currentname);
}
}
count++;
}
// copy sorted nodes to new LinkedList called container
Linkedlist container = new Linkedlist();
for (int i = 0; i < 26; i++) {
Node n = allNameLinkedList[i].front;
while(n != null){
container.addNodeToTheEndOfTheList(n.name);
n = n.next;
}
}
// empty all the elements of array
for (int i = 0; i < allNameLinkedList.length; i++) {
allNameLinkedList[i] = new Linkedlist();
}
Node m = container.front;
while(m!=null)
{
String currentname = m.name;
for(int i = 0; i < 26; i++){
if(currentname.charAt(1) == (char)(i+97))
{
allNameLinkedList[i].addNodeToTheEndOfTheList(currentname);
}
}
m = m.next;
count++;
}
container = new Linkedlist();
for (int i = 0; i < 26; i++) {
m = allNameLinkedList[i].front;
while(m!=null){
container.addNodeToTheEndOfTheList(m.name);
m = m.next;
}
}
for (int i = 0; i < allNameLinkedList.length; i++) {
allNameLinkedList[i] = new Linkedlist();
}
m = container.front;
while(m!=null)
{
String currentname = m.name;
for(int i = 0; i < 26; i++){
if(currentname.charAt(0) == (char)(i+97))
{
allNameLinkedList[i].addNodeToTheEndOfTheList(currentname);
}
}
m = m.next;
count++;
}
container = new Linkedlist();
for (int i = 0; i < 26; i++) {
m = allNameLinkedList[i].front;
while(m!=null){
System.out.println(m.name);
container.addNodeToTheEndOfTheList(m.name);
m = m.next;
}
}
scan.close();
System.out.println("The total number of comparisions was :"+count);
}
}
【问题讨论】:
-
为了将来参考,明智的做法是包含一个简短的、独立的、正确的示例,该示例以最少的文本显示出了什么问题。这将包括您的链表代码。如需了解更多信息,请查看sscce.org
-
代码太多,我不太明白你的问题,你对单词进行了排序,你真正需要什么?
output you should get与基数排序有什么关系?
标签: java sorting data-structures radix-sort