Home > Java > javaTutorial > body text

How to find the maximum value through recursive comparison in Java

王林
Release: 2023-04-24 12:52:15
forward
771 people have browsed it

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>
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template