+ 3

How to find largest and smallest number in unsorted array?

22nd Feb 2017, 6:42 AM
Bukuru Henry
Bukuru Henry - avatar
6 Antworten
+ 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
22nd Feb 2017, 8:40 AM
derek
+ 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);
22nd Feb 2017, 8:42 AM
Tamás Barta
Tamás Barta - avatar
+ 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); }
23rd Feb 2017, 4:31 AM
Kalpesh
+ 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.*"
22nd Feb 2017, 8:35 AM
Art Stesh
Art Stesh - avatar
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.
22nd Feb 2017, 7:48 AM
Raj Kumar Chauhan
Raj Kumar Chauhan - avatar
0
whatsap
22nd Feb 2017, 3:04 PM
bathri narayanan
bathri narayanan - avatar