Find largest and smallest value in array ?
>> In Java, we can find smallest and largest value in given array by using for loop, collections, arrays sort,...
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class largeSmallArray {
public static void main(String[] args) {
int numbers[] = { 2, 4, -3, -4, 0, 10, 5, 20 };
int smallest = numbers[0];
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("largest value in array using for loop=" + largest);
System.out.println("smallest value in array using for loop=" + smallest);
System.out.println("<<---------------------------------------->>");
Arrays.sort(numbers);
System.out.println("Smallest value using arrays sort=" + numbers[0]);
System.out.println("Largest value using arrays sort=" + numbers[numbers.length - 1]);
System.out.println("<<---------------------------------------->>");
Integer b[] = { 1, 2, 5, 6, 3, 2, -1, -2 };
List<Integer> list = Arrays.asList(b);
Collections.sort(list);
System.out.println("Smallest value using collections=" + list.get(0));
System.out.println("Largest value using collections=" + list.get(list.size() - 1));
}
}
Output:
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.