我正在一个项目中,该项目从文件读取数据,将数据放入链接的节点,使用冒泡排序对链接的节点进行排序,然后打印到输出文件。每次以冒泡排序进行交换/交换/通过时,我都要对其进行计数,并打印出对任何给定列表进行排序所花费的交换/交换/通过次数。我的代码似乎工作正常,并且可以正常打印到屏幕上,但是在输出文件中而不是数字中,出现了像“ Ⴖ”之类的奇怪符号?预先感谢!
package assignment1;
import java.io.PrintWriter;
public class Sorting {
private int comparisons;
private int exchanges;
private int totalC;
private int totalE;
private int totalP;
private long time;
private int pass;
private static PrintWriter printWriter;
private static int n; //size list
public Sorting(int size, PrintWriter pw) {
n = size;
printWriter = pw;
}
}
对列表进行排序的方法。 (它已经成功地进行了排序-那里没有问题。但是,我的变量更新或对我的display方法的调用必须是随意的。应该在每次“通过”该方法后进行打印,并打印每次进行的比较和交换次数通过。然后我应该在最后打印所有内容的总和。这是无效的部分。当我尝试为每次迭代打印变量时,我得到了很长的随机符号和字母字符串。
public void bubbleSort(LinkedNode head) {
LinkedNode previous;
LinkedNode current;
LinkedNode next;
comparisons = 0;
exchanges = 0;
time = 0;
pass = 0;
totalC = 0;
totalE = 0;
totalP = 0;
boolean isSorted = true;
//if list is empty or only 1 item is in list -> it is sorted
if (head == null || head.getNext() == null) {
return;
}
long start = System.currentTimeMillis(); //begin count for bubbleSort
while(isSorted) {
comparisons = 0;
exchanges = 0;
previous = null;
current = head;
next = head.getNext();
isSorted = false;
while(next != null) {
comparisons ++; //increment counter for each comparison made
if (current.getElement() > next.getElement()) {
if (head == current) {
head = next;
}
else {
previous.setNext(next);
}
current.setNext(next.getNext());
next.setNext(current);
isSorted = true;
current = next;
exchanges++;
}
previous = current;
current = previous.getNext();
next = current.getNext();
}
pass++; //increment counter for each run through
totalP += pass;
totalE += exchanges;
totalC += comparisons;
}
long elapsedTimeMillis = System.currentTimeMillis()-start;
time = elapsedTimeMillis;
}
正确输出到我的文件的唯一部分是时间变量。在我的屏幕上,通过的次数为4,239,但在输出文件中,我得到了奇怪的符号。
void bubbleSortDisplay(LinkedList myList, PrintWriter pw) {
System.out.printf("time pass cmp exch ");
printWriter.write("time pass cmp exch ");
printWriter.write("\n----------------------------\n");
System.out.printf("\n", time);
printWriter.write(time + "ms ");
System.out.print(time + "ms ");
printWriter.write(totalP);
System.out.print(totalP);
}
尝试以这种方式替换您的代码:
printWriter.write(""+totalP);
(带有空字符串的Concat totalP)