Java Program to Find Smallest Element in Array
int min = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) min = arr[i]; }.Examples
How to Think About It
Algorithm
Code
public class SmallestElement { public static void main(String[] args) { int[] arr = {3, 5, 1, 2, 4}; int min = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; } } System.out.println("Smallest element is: " + min); } }
Dry Run
Let's trace the array [3, 5, 1, 2, 4] through the code to find the smallest element.
Initialize min
min = 3 (first element)
Compare with second element
arr[1] = 5; 5 < 3? No; min stays 3
Compare with third element
arr[2] = 1; 1 < 3? Yes; min updated to 1
Compare with fourth element
arr[3] = 2; 2 < 1? No; min stays 1
Compare with fifth element
arr[4] = 4; 4 < 1? No; min stays 1
Result
Smallest element found is 1
| Iteration | Current Element | min Value |
|---|---|---|
| Start | 3 | 3 |
| 1 | 5 | 3 |
| 2 | 1 | 1 |
| 3 | 2 | 1 |
| 4 | 4 | 1 |
Why This Works
Step 1: Initialize min
We start by assuming the first element is the smallest using min = arr[0].
Step 2: Compare elements
We check each element with if (arr[i] < min) to find if there is a smaller value.
Step 3: Update min
If a smaller element is found, we update min to that element.
Step 4: Final result
After checking all elements, min holds the smallest element in the array.
Alternative Approaches
import java.util.Arrays; public class SmallestElementStream { public static void main(String[] args) { int[] arr = {3, 5, 1, 2, 4}; int min = Arrays.stream(arr).min().getAsInt(); System.out.println("Smallest element is: " + min); } }
import java.util.Arrays; public class SmallestElementSort { public static void main(String[] args) { int[] arr = {3, 5, 1, 2, 4}; Arrays.sort(arr); System.out.println("Smallest element is: " + arr[0]); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so it runs in linear time, O(n), where n is the number of elements.
Space Complexity
It uses only a few variables and no extra arrays, so space complexity is constant, O(1).
Which Approach is Fastest?
The loop method is fastest for this task. Sorting takes O(n log n), and streams add some overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop through array | O(n) | O(1) | Finding smallest element efficiently |
| Arrays.stream().min() | O(n) | O(1) | Concise code with Java 8+ |
| Sorting array | O(n log n) | O(1) | When array needs sorting anyway |