首页 > 其他分享 >使用递归获取数组最大值。(有图)

使用递归获取数组最大值。(有图)

时间:2022-11-04 23:35:19浏览次数:49  
标签:arr 递归 有图 int 最大值 System process test out

package class03;

import java.util.Arrays;

/**
 * 使用递归获取数组最大值
 * 只是用这个获取数组最大值的例子,来理解递归。
 */
public class Code08_GetMax {
    public static int process(int[] arr, int L, int R) {
        if (L == R) {//结束递归的条件。base case
            return arr[L];
        }
        int mid = L + ((R - L) >> 1);//中点。mid = (L + R) / 2
        int leftMax = process(arr, L, mid);//左侧最大
        int rightMax = process(arr, mid + 1, R);//右侧最大
        return Math.max(leftMax, rightMax);
    }

    public static int test(int[] arr, int L, int R) {
        int temp = arr[0];
        for (int i = 0; i < arr.length; i++) {
            temp = Math.max(arr[i], temp);
        }
        return temp;
    }

    public static int[] generatorRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) (Math.random() * maxSize) + 2];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * maxValue);
        }
        return arr;
    }

    public static void main(String[] args) {
        int maxSize = 10;
        int maxValue = 10;
        int testTimes = 10;
        System.out.println("test start!");
        for (int i = 0; i < testTimes; i++) {
            int[] arr = generatorRandomArray(maxSize, maxValue);
            int N = arr.length;
            int test = test(arr, 0, N - 1);
            int process = process(arr, 0, N - 1);
            if (test != process) {
                System.out.println("oops!");
                System.out.println("arr = " + Arrays.toString(arr));
                System.out.println("test = " + test);
                System.out.println("process = " + process);
                break;
            }
        }
        System.out.println("test end!");
    }

}

 

标签:arr,递归,有图,int,最大值,System,process,test,out
From: https://www.cnblogs.com/TheFloorIsNotTooHot/p/16859447.html

相关文章