[Java] How to find min number from an array?
I want to find the minimum number from an array, how can I do that in Java?
1 Answer
3 years ago by Eleven
1. Simplest way to find the smallest number
We have Arrays.sort()
utility available to sort the elements from an array, using this we can sort the array first, then we can pick the first element to find the smallest element.
Following code shows that
import java.util.Arrays;
public class JavaArrays {
public static void main(String[] args) {
int[] numbers = { 22, 456, 97, 4 };
Arrays.sort(numbers);
System.out.println("Smallest number from the array: " + numbers[0]);
}
}
Try it here: https://onecompiler.com/java/3xmstnz4h
2. Efficient way to find smallest number
In Java you can iterate though an array to find the smallest number of an array.
Following program shows how to do that
public class JavaArrays {
public static void main(String[] args) {
int[] numbers = { 22, 456, 97, 4 };
System.out.println("Smallest number from the array: " + minMumber(numbers));
}
static int minMumber(int[] numbers) {
int min = numbers[0];
for (int ele : numbers) {
if (ele < min) {
min = ele;
}
}
return min;
}
}
Try it here: https://onecompiler.com/java/3xmstpwhp
3 years ago by Karthik Divi