代码之家  ›  专栏  ›  技术社区  ›  akisonlyforu

为什么我的函数没有给出正确的输出?

  •  1
  • akisonlyforu  · 技术社区  · 7 年前

    我的函数检查数组是否使用递归排序。 不幸的是,它又回来了 false 对于每个数组。

    Function call : sorted(a,0,a.length) where a[] = {1,2,3}; 
    
    boolean sorted(int[] a , int s , int n)
    {
        if(s+1==n)
            return true ;
        if(a[s]<=a[s+1])
            sorted(a,s+1,n);
        return false ;
    }
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   David Conrad    7 年前

    您忽略了对的递归调用的结果 sorted . 只要把它还给我,你就可以了:

    boolean sorted(int[] a , int s , int n)
    {
        if(s+1==n)
            return true ;
        if(a[s]<=a[s+1])
            return sorted(a,s+1,n); // Here!      
        return false ;
    }
    
        2
  •  1
  •   MBo    7 年前

    您不使用递归调用的结果。也许看起来像

     if(a[s]<=a[s+1])
          return sorted(a,s+1,n)
     else
         return false;
    

    或者(如果Java使用复杂条件的快速评估):

    return (a[s]<=a[s+1]) && (sorted(a,s+1,n))