-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP25_FindLargestAndSmallest.java
More file actions
36 lines (29 loc) · 1.11 KB
/
Copy pathP25_FindLargestAndSmallest.java
File metadata and controls
36 lines (29 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package programs;
import java.util.Arrays;
/**
* ============================================================
* PROGRAM 25: Find Largest and Smallest Element in Array
* ============================================================
* Problem: WAP to find the maximum and minimum elements in an array in O(n).
* ============================================================
*/
public class P25_FindLargestAndSmallest {
public static void findMinMax(int[] arr) {
if (arr == null || arr.length == 0) {
System.out.println("Array is empty.");
return;
}
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
System.out.println("Array : " + Arrays.toString(arr));
System.out.printf(" Min : %d | Max : %d | Difference (Span): %d%n", min, max, (max - min));
}
public static void main(String[] args) {
findMinMax(new int[]{45, 12, 89, 32, 99, 1, 67, 34});
findMinMax(new int[]{-10, -5, -80, -2, -15});
}
}