Find the smallest and largest elements in an array
This is one very interesting question that is often asked in coding interviews.
The goal is to find the smallest and largest elements in an array but without using sorting.
The following is a good example of code written in Java:
public static void main(String[] args) {
int[] arr = {8, 42, 7, 13, 22, 32, 14, 9, 11};
printSmallestAndLargest(arr);
}
public static void printSmallestAndLargest(int[] arr) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
} else if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("The smallest element is: " + min);
System.out.println("The largest element is: " + max);
} Output:
The smallest element is: 7
The largest element is: 42
That is all about how to find the smallest and largest elements in an array.
No comments:
Post a Comment