w3resource

Java Recursive Method: Find the maximum element

Java Recursive: Exercise-12 with Solution

Recursive Maximum in Array

Write a Java recursive method to find the maximum element in an array.

Sample Solution:

Java Code:

import java.util.Arrays;
public class ArrayMaxElementFinder {

  public static int findMaxElement(int[] arr) {
    return findMaxElement(arr, 0, arr.length - 1);
  }

  private static int findMaxElement(int[] arr, int left, int right) {
    // Base case: if the left and right indices are equal, 
    // we have a single element and return it as the maximum
    if (left == right) {
      return arr[left];
    }

    // Recursive case: divide the array into two halves, recursively 
    //find the maximum in each half,and return the greater of the 
    // two maximums
    int mid = (left + right) / 2;
    int maxLeft = findMaxElement(arr, left, mid);
    int maxRight = findMaxElement(arr, mid + 1, right);

    return Math.max(maxLeft, maxRight);
  }

  public static void main(String[] args) {
    int[] array = {
      34,
      45,
      34,
      23,
      56,
      62,
      27,
      55
    };
    System.out.println("Original Array: " + Arrays.toString(array));
    int maxElement = findMaxElement(array);
    System.out.println("The maximum element in the array is: " + maxElement);
  }

Sample Output:

Original Array: [34, 45, 34, 23, 56, 62, 27, 55]
The maximum element in the array is: 62

Explanation:

In the above exercises -

First, we define a class ArrayMaxElementFinder that includes a recursive method findMaxElement() to find the maximum element in an array.

The findMaxElement() method has two cases:

  • Base case: If the left and right indices are equal, we have a single element and return it as the maximum element.
  • Recursive case: For any array with more than one element, we divide the array into two halves by finding the middle index. We then recursively find the maximum element in each half by calling the method with the appropriate indices. Finally, we return the higher value of the two maximums obtained from the recursive calls.

In the main() method, we demonstrate the findMaxElement() method by finding the maximum element in the array [34, 45, 34, 23, 56, 62, 27, 55] and printing the result.

Flowchart:

Flowchart: Java  recursive Exercises: Find the maximum element.

Java Code Editor:

Java Recursive Previous: Generate all possible permutations.
Java Recursive Next: Calculate the product of numbers in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/recursive/java-recursive-exercise-12.php