-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSecondLargestElementInArray.java
More file actions
36 lines (36 loc) · 1.16 KB
/
SecondLargestElementInArray.java
File metadata and controls
36 lines (36 loc) · 1.16 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
public class SecondLargestElementInArray {
public static void main(String[] args) {
int arr[] = { 10, 20, 5, 15, 11, 12, 20 };
int max = -1;
int secondLargest = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
secondLargest = max;
max = arr[i];
}
if (arr[i] != max) {
// Checking Dup
// make sure current element is not the first largest
if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
}
System.out.println("First " + max + " Second " + secondLargest);
// for (int i = 1; i < arr.length; i++) {
// if (arr[i] > max) {
// max = arr[i];
// }
// }
// System.out.println("First Largest " + max);
// int secondLargest = arr[0];
// for (int i = 1; i < arr.length; i++) {
// if (arr[i] != max) {
// if (arr[i] > secondLargest) {
// secondLargest = arr[i];
// }
// }
// }
// System.out.println("Second Largest " + secondLargest);
}
}