Skip to content

Commit 42ec19b

Browse files
authored
Second Largest file added
1 parent ee6f858 commit 42ec19b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Coding/second_largest.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Java program to find second largest
2+
// element in an array
3+
import java.util.*;
4+
class Secondlargest{
5+
6+
// Function to print the
7+
// second largest elements
8+
static void print2largest(int arr[],
9+
int arr_size)
10+
{
11+
int i, first, second;
12+
13+
// There should be
14+
// atleast two elements
15+
if (arr_size < 2)
16+
{
17+
System.out.printf(" Invalid Input ");
18+
return;
19+
}
20+
21+
// Sort the array
22+
Arrays.sort(arr);
23+
24+
// Start from second last element
25+
// as the largest element is at last
26+
for (i = arr_size - 2; i >= 0; i--)
27+
{
28+
// If the element is not
29+
// equal to largest element
30+
if (arr[i] != arr[arr_size - 1])
31+
{
32+
System.out.printf("The second largest " +
33+
"element is %d\n", arr[i]);
34+
return;
35+
}
36+
}
37+
38+
System.out.printf("There is no second " +
39+
"largest element\n");
40+
}
41+
42+
// Driver code
43+
public static void main(String[] args)
44+
{
45+
int arr[] = {12, 35, 1, 10, 34, 1};
46+
int n = arr.length;
47+
print2largest(arr, n);
48+
}
49+
}
50+
51+

0 commit comments

Comments
 (0)