Home >Java >javaTutorial >How to find the maximum value through recursive comparison in Java

How to find the maximum value through recursive comparison in Java

王林
王林forward
2023-04-24 12:52:15788browse

Recursive comparison

The core of recursive comparison is to first define two positions (starting position and ending position), and compare the starting position and ending position each time. When the starting position is greater than the ending position, value, set the maximum value to the value of the start position, then set the end position -1 (move one bit forward), and continue the recursive call; on the contrary, when the value of the end position is greater than the start position, set the maximum value to the end position value, set the starting position to 1 (move one bit back), continue to call the comparison recursively, and return the maximum value until the end of the recursion. The execution process is as shown in the figure below:

How to find the maximum value through recursive comparison in Java


The implementation code is as follows:

<code>public class ArrayMax {<br>    public static void main(String[] args) {<br>        int[] arr = {3, 7, 2, 1, -4};<br>        int max = findMaxByRecursive(arr, 0, arr.length - 1, 0); // 根据 Collections 查找最大值<br>        System.out.println("最大值是:" + max);<br>    }<br><br>    /**<br>     * 根据递归查询最大的值<br>     * @param arr  待查询数组<br>     * @param head 最前面的元素的下标<br>     * @param last 最末尾的元素的下标<br>     * @param max  (临时)最大值<br>     * @return 最大值<br>     */<br>    private static int findMaxByRecursive(int[] arr, int head, int last, int max) {<br>        if (head == last) {<br>            // 递归完了,返回结果<br>            return max;<br>        } else {<br>            if (arr[head] > arr[last]) {<br>                max = arr[head]; // 赋最大值<br>                // 从后往前移动递归<br>                return findMaxByRecursive(arr, head, last - 1, max);<br>            } else {<br>                max = arr[last]; // 赋最大值<br>                // 从前往后移动递归<br>                return findMaxByRecursive(arr, head + 1, last, max);<br>            }<br>        }<br>    }<br>}<br></code>

The execution result of the above program is:

The maximum value is: 7

The above is the detailed content of How to find the maximum value through recursive comparison in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete