2016-05-13 8 views
0

現在、アルゴリズムはn個の整数のシーケンスですべての並べ替えを出力するようになっていますが、この関数は6つの要素まで正常に動作しますが、それ以上の場合はStackOverflowErrorメッセージ。私はこのトピックに関するいくつかの質問を読んだことがあるが、私が知ったことは、再帰的メソッドが無限大の呼び出しを持ち、ベースケースが実行されているようではないように見えることである。再帰的メソッドのjava.lang.StackOverflowError

//int[] c parameter receives an array with n elemens to permute 
//int i represents the length of the sequence to permute (ai,...,aN) 
public boolean isPermutated(int[] c, int i) 
{ 
    int max = 0; // the maximum number from a sequence (a1,...,aN) and 
    int index = 0; // the index where the maximum is 
    int lessThan; // an index preceded by maximum 
    //Base case 
    if(i == 1) 
    { 
     return false; 
    }   
    // Gives the Maximum element from a sequence (ai,...,aN) 
    for(int count = c.length - i; count < c.length; count++) 
    { 
     if(max < c[count]) 
     { 
      max = c[count]; 
      index = count; 
     } 
    } 
    // Swap the Maximum from index to index-1 
    if(max != c[c.length - i]) 
    { 
     lessThan = c[index-1]; 
     c[index-1] = max; 
     c[index] = lessThan; 
     //move each maximum from a sequence (a,...,aN) to the last index ex, (3,2,1)->(2,1,3) 
     if(i != c.length) 
     { 
      while((i-c.length) != 0) 
      { 
       for(int count = c.length - (i+1); count < c.length-1; count++) 
       { 
        int before; 
        int after; 
        before = c[count]; 
        after = c[count+1]; 
        c[count] = after; 
        c[count+1] = before;  
       } 
       i++; 
      } 
     } 

     // print array c elements  
     for(int e:c) 
      System.out.print(e); 
     System.out.println(); 
     isPermutated(c, c.length);  
    } 
    else 
    { 
     i--; 
     isPermutated(c, i);   
    } 
    return true; 
} 

私は10要素の配列でそれを必要とするので、私はただ不満です。同じメソッドシグネチャを持つ擬似コードはありますか、それとも部分的に問題を解決するはずなので、スタックトレースを微調整する方法はありますか?

+0

エラーの原因となるコードを追加してください。 – maxpovver

+1

現実のことについてのあなたの前提は、現実に合っていません。デバッガのコードをスピンアップして、なぜそれが起こっているのかを見てください。さらに、クラスを実行して複雑さを増強するJunitテストを書くことを開始してください。 – duffymo

+2

スタックオーバーフローは、コールスタックがオーバーフローした場合に発生します。これは、有限数のコールであり、無限のコールではありません。 – SamTebbs33

答えて

3

あなたのコードには返信文がありませんか?なぜあなたは再取得された値を気にせずにisPermutatedを呼び出しますか?

コードは決してtrueを返しません。

関連する問題