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