How to Find Smallest Element in Array in Java
The Challenge
Find the minimum (smallest) element in an array!
Solutions
Method 1: Using Loop
int[] numbers = {5, 2, 8, 1, 9};
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
System.out.println("Smallest: " + min);
// Output: Smallest: 1Method 2: Using Arrays.sort()
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
int min = numbers[0];
System.out.println("Smallest: " + min);
// Output: Smallest: 1Method 3: Using Java 8 Streams
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("Smallest: " + min);
// Output: Smallest: 1Did You Know?
The loop method is most efficient with O(n) time complexity. Sorting is O(n log n) but gives you a sorted array as a bonus!
Pro Tip
Use Integer.MAX_VALUE as initial min value to handle all cases safely!
Real-World Use Cases
- E-commerce: Find lowest price
- Weather: Find minimum temperature
- Gaming: Find lowest score
- Analytics: Find minimum value in dataset
›Short versionOpen if you only have a minute.
- One pass is enough. Sorting is O(n log n) and reorders the array.
- Start min at the first element, not at 0.
- A min that starts at 0 stays 0 when every element is positive, so the result is not in the array.
- An empty array has no first element. Refuse it.
Smallest element
Find the lowest value by scanning the array once.
Working approach
- Reject a null or empty array.
- Set min to values[0].
- Replace min whenever a later element is smaller.
Walk the sample
- Values 8, 3, 5
- min starts at 8
- 3 replaces it
- 5 does not
- The result is 3
The trap
int min = 0 never updates on {3, 8, 5}, because nothing is less than 0. The method returns a value that is not in the array.
static int smallest(int[] values) {
if (values.length == 0) {
throw new IllegalArgumentException("empty array");
}
int min = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}Why does int min = 0 fail for {3, 8, 5}?
Every element is greater than 0, so the condition never fires and min stays 0. 0 is not in the array.
An all-negative array happens to update a 0 initializer, because those values are smaller than 0. The all-positive array does not. Start from the first element and both cases are covered.
Time O(n), space O(1).
Easy to get wrong
- Initializing min to 0.
- Sorting the array to read index 0.