【知识积累】求数组arrays中的最大值

package com.example.demo.algorithm.D002;

/**
 * @Description :
 * 理解递归
 *
 * 求数组arrays中的最大值
 *
 * 求数组arr[L ... R]中的最大值,怎么用递归方法实现
 * 1)将[L ... R]分成左右两半。左[L ... Mid] 右[Mid+1 ... R]
 * 2)左部分求最大值,有部分求最大值
 * 3)[L ... R]范围上的最大值,是max(左部分求最大值,有部分求最大值)
 *
 * 注意:2)是个递归过程,当范围上只有一个数,就可以不用再递归了
 *
 * [5, 8, 4, 6]
 *  0  1  2  3
 *            f(0,3)
*      f(0,1)       f(2,3)
 * f(0,0) f(1,1) f(2,2) f(3,3)
 *
 * f(0,3) -> mid=1, leftMax=?, rightMax=?, lineNumber=18
 *
 * f(0,1) -> mid=1, leftMax=?, rightMax=?, lineNumber=8
 * f(0,0) -> leftMax=5
 * f(1,1) -> rightMax=8
 *
 * f(2,3) -> mid=2, leftMax=?, rightMax=?, lineNumber=6
 * f(2,2) -> leftMax=4
 * f(3,3) -> rightMax=6
 *
 * @Author : Darren
 * @Date : 2021 年 02 月 18 日 22:11:41
 * @since : 1.0
 */
public class J008_GetArrayMax {

    public static void main(String[] args) {
        int maxSize = 10;
        int maxValue = 10;
        int testTimes = 10;
        for (int i = 0; i < testTimes; i++) {
            int[] arrays = generateRandomArray(maxSize, maxValue);
            printArray(arrays);
            System.out.println(getMax(arrays));
            System.out.println();
        }
    }

    public static int getMax(int[] arrays){
        return process(arrays, 0, arrays.length - 1);
    }

    private static int process(int[] arrays, int L, int R) {
        //arrays只有一个数,直接返回
        if (L == R){
            return arrays[L];
        }
        //中点位置
        int mid = L + ((R - L) >> 1);
        int leftMax = process(arrays, L, mid);
        int rightMax = process(arrays, mid+1, R);
        return Math.max(leftMax, rightMax);
    }

    /**
     * 生成一个随机数组
     * @param maxSize
     * @param maxValue
     * @return
     */
    public static int[] generateRandomArray(int maxSize, int maxValue){
        //Math.random() [0,1)
        //Math.random() * N [0,N)
        //(int)(Math.random() * N) [0,N-1]
        int[] arrays = new int[(int) ((maxSize+1) * Math.random())];
        for (int i = 0; i < arrays.length; i++) {
            arrays[i] = (int) ((maxValue+1) * Math.random()) - (int)(maxValue * Math.random());
        }
        return arrays;
    }

    /**
     * 打印数组
     * @param arrays
     */
    public static void printArray(int[] arrays){
        if (arrays == null){
            return;
        }
        for (int i = 0; i < arrays.length; i++) {
            System.out.print(arrays[i] + " ");
        }
        System.out.println();
    }

}

猜你喜欢

转载自blog.csdn.net/axin1240101543/article/details/113846285
今日推荐