0
我想知道是否可以打印出每一步。這裏是我的代碼: ,你可以看到,我傳入一個鏈表,我複製到一個數組的值可能使我的排序生活更容易,然後將排序後的數組寫入單獨的文本文件。打印類似的步驟
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Insertion
{
public void Sort (LinkedList listIn, int size) throws Exception
{
String[] insArray = new String[size] ;
String textContent = null ;
File outputFile ;
//copy the list values in the array
for (int i = 0 ; i < size ; i++)
{
insArray [i] = listIn.get(i).printNode();
}
Stopwatch timer = new Stopwatch().start();
//Insertion Sort
for (int i = 1; i < size; i++)
for (int j = i; j > 0; j--)
{
if (insArray[j-1].compareToIgnoreCase(insArray[j]) > 0)
{
replace(insArray, j, j-1);
}
}
timer.stop();
do
{
outputFile = new File("[Insertion] Sorted Entries.txt") ;
if(!outputFile.exists())
{
outputFile.createNewFile();
System.out.println("Sorted file created.txt");
System.out.println("");
}
else
{
System.out.println("File Updated.");
}
}while (!outputFile.exists()) ;
try
{
//the "true" argument sets the FileWriter to append mode so that is does not overwrite the first line
BufferedWriter out = new BufferedWriter(new FileWriter("[Insertion] Sorted Entries.txt", true));
for (int i = 0 ; i < size ; i++)
{
textContent = (insArray[i]) ;
out.write(textContent) ;
out.newLine() ;
}
out.close() ;
}catch(IOException e)
{
System.out.println("Could not write to file") ;
System.exit(0) ;
}
System.out.println("Time to execute: " + timer.getElapsedTime() + "ns");
}
private static void replace(Comparable[] array, int i, int j)
{
Comparable swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
我正在嘗試制定一個假設,以解釋您編寫此代碼的事實以及代碼已經清楚地顯示如何記錄算法的每個步驟的事實。你能幫助我嗎? – 2012-04-19 09:50:19
在for(int i = 1; i
2012-04-19 09:53:50
對於我來說這個問題並不完全清楚。你的意思是在每個分揀步驟之後打印insArray的狀態?在調用replace之前,添加代碼以將insArray的內容寫入文件或stdout中? – Matthias 2012-04-19 09:54:05