2016-05-13 58 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

你的代碼不會錯過返回語句嗎?你爲什麼打電話是不需要擔心價值重塑?

您的代碼永遠不會返回true。