-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecond_Largest.java
More file actions
52 lines (48 loc) · 1.37 KB
/
Second_Largest.java
File metadata and controls
52 lines (48 loc) · 1.37 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Arrays;
public class Second_Largest {
// public int getLargest(int arr[], int n) {
// int res = 0;
// for(int i=1; i<arr.length; i++) {
// if(arr[i] > arr[res]) {
// res = i;
// }
// }
// return res;
// }
// public int getSecond(int arr[]) {
// int largest = getLargest(arr, arr.length);
// int res=-1;
// for(int i=1; i<arr.length; i++) {
// if(arr[i] != arr[largest]) {
// if(res == -1){
// res=i;
// }
// else if(arr[i] > arr[res]){
// res = i;
// }
// }
// }
// return res;
// }
public int secondLargest(int arr[], int n) {
int res = -1;
int largest = 0;
for(int i=0; i<arr.length; i++) {
if(arr[i] > arr[largest]){
res= largest;
largest=i;
}
else if(arr[i] != arr[largest]) {
if(res == -1 || arr[i] > arr[res]) {
res=i;
}
}
}
return res;
}
public static void main(String[] args) {
Second_Largest obj = new Second_Largest();
int arr[] = {5, 8, 20, 10};
System.out.println(obj.secondLargest(arr, arr.length));
}
}