java递归方法求数组最大元素


一直对递归写法不是很熟悉,特写一个增进理解

/**
 * Created by Administrator on 2017-11-01.
 */
public class recursion {
    private static int max(int a,int b){   //定义一个比较两个数值大小的函数
        return a>b?a:b;
    }
    public static int maxNum(int[] arr,int endindex){   //采用的递归思路是:若求长度为L的数组最大值,即是求 数组前L-1个长度的最大值 和最后一个数组元素的相对较大值
        if(endindex==0){
            return arr[0];
        }
        return max(arr[endindex],maxNum(arr,endindex-1));
    }
    public static void main(String[] args){
        int array[]= {6,1,5,4,8,3,9,12,51,11,15,14,13,25,69,47,56,74,26,78};
        System.out.print(maxNum(array,array.length-1));
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM