首先,我想指出这项作业是家庭作业/but/我不是在寻找直接答案,而是在提示 或关于我的实现为何不起作用的一些见解。
这是给定的:我们得到了一个单词列表,每个单词长 7 个字符,并被要求在使用队列时使用基数排序算法对它们进行排序。
编辑 1:更新代码
这是我的代码:
import java.util.*;
import java.io.File;
public class RadixSort {
public void radixSort() {
ArrayList<LinkedQueue> arrayOfBins = new ArrayList<LinkedQueue>();
LinkedQueue<String> masterQueue = new LinkedQueue<String>();
LinkedQueue<String> studentQueue = new LinkedQueue<String>();
//Creating the bins
for (int i = 0; i < 26; i++) {
arrayOfBins.add(new LinkedQueue<String>());
}
// Getting the file name and reading the lines from it
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with its extension: ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
masterQueue.enqueue(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
for (int p = 6; p >= 0; p--) {
for (LinkedQueue queue : arrayOfBins) {
queue.clear();
}
while (masterQueue.isEmpty() == false) {
String s = (String) masterQueue.dequeue();
char c = s.charAt(p);
arrayOfBins.get(c-'a').enqueue(s);
}
for (LinkedQueue queue : arrayOfBins) {
studentQueue.append(queue);
}
}
masterQueue = studentQueue;
System.out.println(masterQueue.size());
System.out.println(masterQueue.dequeue());
}
public static void main(String [] args) {
RadixSort sort = new RadixSort();
sort.radixSort();
}
}
最佳答案
我能看到这么多问题,我完全不确定你是如何得到答案的。
- 为什么从 0 到 6 有两个嵌套的最外层循环?
- 你为什么不清除
studentQueue
? - j 循环的执行次数并没有您想象的那么多。
除了明确的错误之外,该程序没有输出任何内容——您是否只是在调试器中查看结果?另外,您是否真的可以假设这些词除了小写字母外不包含其他字符?
关于java - 为什么我的基数排序算法返回一个部分排序的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35618191/