forked from itsprueba/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfind2nd_largest_number_in_an_array.java
More file actions
51 lines (42 loc) · 1004 Bytes
/
find2nd_largest_number_in_an_array.java
File metadata and controls
51 lines (42 loc) · 1004 Bytes
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
/**
* JAVA Code for Find Second largest element in an array
*/
class SecondLargetNumber {
public static void print2largest(int arr[],
int arr_size)
{
int i, first, second;
if (arr_size < 2) {
System.out.print(" Invalid Input ");
return;
}
first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MIN_VALUE)
System.out.print("There is no second largest"
+ " element");
else
System.out.print("The second largest element"
+ " is " + second); // 45
}
public static void main(String[] args)
{
int arr[] = { 22, 35, 45, 10, 54, 1 };
int n = arr.length;
print2largest(arr, n);
}
}
/**
Input: arr[] = {22, 35, 45, 10, 54, 1}
Output: The second largest element is 45.
Explanation: The largest element of the
array is 54 and the second
largest element is 34
*/