递归算法

据说凡是可以循环的步骤,都可以递归表示出来。

递归的关键有二点:
1.0 递归公式,即递推式。
2.0 递归出口。


递归求数组的和

package day20180407;
public class Sumarry {
    public static void main(String[] args) {
      int[] arry= {1,2,3,4,5};
      System.out.println("the sum of the arry="+sum(arry,arry.length-1));
    }
    
    static int  sum(int[] arry,int n)
    {
        if(n==0)
        {
            return arry[0];
        }
        else 
        {
          return sum(arry,n-1)+arry[n];
        
        }
        
    }

}

结果是

the sum of the arry=15

求数组的最大数

package day20180407;
public class Maxarry {
     static int count=0;
    public static void main(String[] args) {
    
          int[] arry= {1,2,3,4,5,88,-85,1};
          System.out.println("the max of the arry="+max(arry,arry.length-1));
          System.out.println("count function="+count);
    }
    
    static int max(int[] arry,int n)
    {
       count++;
       if(n==0) 
       {
           return arry[0];
       }
       else
       {
           if(max(arry,n-1)>arry[n])
           return max(arry,n-1);
           else
          return arry[n];
           
       }
        
    }

}

结果是:

the max of the arry=88
count function=27

可以看成这个函数,递归了20多次,你能理解其过程嘛,反正计算机可以。 我感觉递归就像一种哲学。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容