Find Largest Element in an Array
Understanding Finding Largest Element
Finding the largest element in an array involves scanning the array and keeping track of the maximum value encountered.
We will explore three different methods to find the largest element in an array using Java.
Method 1: Using Iteration
This method iterates through the array and finds the largest element.
public class LargestElement { public static void main(String[] args) { int[] arr = {10, 20, 4, 45, 99, 23}; int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } System.out.println("Largest element: " + max); } }
Method 2: Using Sorting
This method sorts the array and takes the last element as the largest.
import java.util.Arrays; public class LargestElementSort { public static void main(String[] args) { int[] arr = {10, 20, 4, 45, 99, 23}; Arrays.sort(arr); System.out.println("Largest element: " + arr[arr.length - 1]); } }
Method 3: Using Recursion
This method finds the largest element using recursion.
public class LargestElementRecursion { public static int findMax(int[] arr, int n) { if (n == 1) return arr[0]; int max = findMax(arr, n - 1); return Math.max(arr[n - 1], max); } public static void main(String[] args) { int[] arr = {10, 20, 4, 45, 99, 23}; System.out.println("Largest element: " + findMax(arr, arr.length)); } }