-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSecondHighest.java
More file actions
40 lines (35 loc) · 1.07 KB
/
Copy pathSecondHighest.java
File metadata and controls
40 lines (35 loc) · 1.07 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
package array;
public class SecondHighest {
static int arr[] = {12, 34, 10, 6, 40};
public static void main(String[] args){
System.out.println("Second Highest is: " + secondHighest());
}
static int secondHighest() {
// Initialize first and second largest element
int first, second;
if (arr[0] > arr[1])
{
first = arr[0];
second = arr[1];
}
else
{
first = arr[1];
second = arr[0];
}
for (int i = 2; i<arr.length; i++)
{
/* If current element is greater than first then update both
first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
return (second);
}
}