How to Find the Maximum Element in an Array?

In Java, the array is a data structure that allows the users to store data of the same type in contiguous memory locations. In this article, we will learn how to find the maximum element in an array in Java.

Example of finding the Maximum Element in an Array

Input: arr= {20,10,5,40,30}
Output: The maximum element in the array is 40.

Find the Maximum Element in an Array

To find the maximum element in an Array in Java, we can sort the array in ascending order using the Arrays.sort() method and then we can access the last element of the array which will be the maximum element of the array.

Java Program to Find the Maximum Element in an Array

The following program illustrates how we can find the maximum element in an array in Java:

Java
// Java program to find the maximum element in an array
import java.util.Arrays;

public class MaxElementFinder {
    // Function to find the max element in an array
    public static int findMaximum(int[] arr) {
        // sort the array in ascending order
        Arrays.sort(arr);
        // return the last element of the sorted array
        return arr[arr.length - 1];
    }
    
    public static void main(String[] args) {
        // Initialize an array of integers
        int[] arr = { 20,10,5,40,30};
        // Find the maximum element of the array
        int max = findMaximum(arr);
        // Print the maximum element of the array
        System.out.println("The Maximum element in the array is : " + max);
    }
}

Output
The Maximum element in the array is : 40

Complexity of the above method:

Time Complexity: O(NlogN), where N is the size of the array.
Auxiliary Space: O(1), as no extra space is used.

Explanation of the above program:

  • We declared a method findMaximum inside the MaxElementFinder class to find the maximum element of the array.
  • Sorted the array in ascending order using the Arrays.sort() method.
  • Returned the last element of the sorted array , which is the maximum element of the array.