2012-04-19 11 views
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; 
    } 
} 
+2

私は、あなたがこのコードを書いたという事実と、コードがアルゴリズムの各ステップをどのように記録するかを明確に示しているという事実の両方を説明する仮説を解いています。あなたはそれで私を助けることができますか? –

+0

for(int i = 1; i

+0

私に質問は完全にはっきりしません。並べ替えのたびにinsArrayの状態を表示することを意味しますか? replaceを呼び出す前にinsArrayの内容をファイルまたはstdoutに書き込むコードを追加するのと同じですか? – Matthias

答えて

0

申し訳ありませんが、疲れた目のため...このようなものが役に立つのでしょうか?

for (int i = 1; i < size; i++) 
     for (int j = i; j > 0; j--) 
     { 
      final int cmp = insArray[j-1].compareToIgnoreCase(insArray[j]); 
      System.out.format("Comparing %s at %d to %s at %d, result %d\n", 
       insArray[j-1], j-1, insArray[j], j, cmp); 
      if (cmp > 0) replace(insArray, j, j-1); 
     } 
関連する問題