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