+ 3
How to find largest and smallest number in unsorted array?
6 odpowiedzi
+ 3
if you are not using an arraylist you can run the array through a for statement and a if statement, then assign the number to one of the variables if it is small or larger than what the current value is for the low and high variable
+ 2
Maybe the shortest way is the new stream API:
int[] array = {3, 5, 6, 1};
int min = java.util.Arrays.stream(array).min().getAsInt();
System.out.println(min);
+ 2
May be this code will help you ::
public static void main (String[] args) {
int arr = new int[]{45, 56, 77, 24, 12, 98};
int max = arr[0];
int min = arr[0];
for(int i = 1; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i];
} else if(arr[i] < min) {
min = arr[i];
}
}
System.out.println("Largest number : " + max);
System.out.println("Smallest number : " + min);
}
+ 1
Integer[] array = new Integer[]{5,9,3,5,2,8};
List<Integer> list = Arrays.asList(array);
System.out.println("max = " + Collections.min(list));
System.out.println("min = " + Collections.min(list));
Output:
max = 9
min= 2
Don't forget to add "import java.util.*"
0
I don't know much about java, it may have min, max function.
but manually you can do like this:
pick first element from array and say it max, now run through array and compare its value if array value is greater than max, update max..keep doing it till last element of array.
and for min...check for lesser values and keep updating it.
0
whatsap