2016-03-27 8 views
1
を使用するまで

私はこのアルゴリズムをシミュレートするヘルプそれコードへ:/ジャワ

public class Test { 



public static void main(String[] args) { 
    int[] a = {5,3,1,9,8,2,4,7}; 
    int l = 0; 
    int p = a[l]; 

    int i=l; 

    int j = 8; 
    do{ 
     do{ 
      i++; 
      System.out.println("Value of i " + i); 

     }while(a[i]>=p); 
     do{ 
      j--; 
      System.out.println("\nValue of j " + j); 

     }while(a[j]<p); 
     swap(a,i,j); 
     System.out.println("\nSwapped! a[i] = " + a[i] + " a[j] = " + a[j]); 
     System.out.println("Swap 1"); 
     for(int k : a){ 
      System.out.print(k + " "); 

     } 

    }while(i>=j); 
    if(i>=j){ 
     swap(a,i,j); 
     System.out.println("\nSwapped! a[i] = " + a[i] + " a[j] = " + a[j]); 
     System.out.println("Swap 2"); 
     for(int k : a){ 
      System.out.print(k + " "); 

     } 
    } 
    else{ 
     swap(a,i,j); 
     System.out.println("\nSwapped! a[i] = " + a[i] + " a[j] = " + a[j]); 
     System.out.println("Swap 3"); 
     for(int k : a){ 
      System.out.print(k + " "); 

     } 
     swap(a,l,j); 
     System.out.println("\nSwapped! a[l] = " + a[l] + " a[j] = " + a[j]); 
     System.out.println("Swap 4"); 
     for(int k : a){ 
      System.out.print(k + " "); 

     } 

    } 


    System.out.println("\nreturn value is: " + j); 

    System.out.println("Final array: "); 
    for(int k : a){ 
     System.out.print(k + " "); 
    } 

} 

public static void swap(int a[], int a1, int a2){ 
    int temp = a[a1]; 
    a[a1] = a[a2]; 
    a[a2] = temp; 
} 

} 

結果は次のとおりです。

enter image description here

しかし、私は紙でそれをシミュレートするとき、私の結果は異なります。それは私が間違って "繰り返す"か "しばらくする"か、紙で間違って分析したかのどちらかです。

あなたのシミュレーションメイトを共有してください:)ありがとう!

答えて

2

それは私が間違って紙で分析dowhileかについてuntilrepeat私が間違ってどちらかです。

repeat/untilを間違って翻訳しました。

The construct comes from Pascal-like languages.それはdo/whileに類似しているが、条件の意味が完全に反対である:do/whileで終了条件は、継続条件あるが、repeat/until状態は終了条件であります

この問題の修正プログラムは、repeat/untilループの条件反転さ:

do{ 
    i++; 
    System.out.println("Value of i " + i); 
} while(a[i]< p); 
//  ^
+0

おかげで男を!今私の論文のシミュレーションと同じ結果が出ました。あなたの明確化のために大きな感謝! :) – Andre