2016-05-13 37 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。