Skip to content

Commit cda18d7

Browse files
committed
Add examples for second laregst element in an array
1 parent f094820 commit cda18d7

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.coderolls.JavaPrograms.second_largest;
2+
/**
3+
* A Java program to find the second largest number in an array
4+
* by iterating over an array using for loop.
5+
*
6+
* @author coderolls.com
7+
*/
8+
public class SecondLargestElementInArray {
9+
10+
public static void main(String[] args) {
11+
int[] arr = {2, 5, 9, 8, 11, 18, 13};
12+
13+
int secondLargest = getSecondLargest(arr);
14+
System.out.println("The second largest element in an array 'arr' is :"+ secondLargest);
15+
}
16+
17+
private static int getSecondLargest(int[] arr) {
18+
int n =arr.length;
19+
int largest =arr[0];
20+
int secondLargest = -1;
21+
22+
for(int i=0; i<n; i++) {
23+
if(arr[i]>largest) {
24+
//if you found the new largest,
25+
//copy current largest to second largest and
26+
//copy current element arr[i] to largest
27+
secondLargest = largest;
28+
largest = arr[i];
29+
}else if(arr[i]!=largest) {
30+
// if the current element arr[i] is not the largest and
31+
// still larger than the current secondLargest
32+
// then copy it to secondLargest
33+
if(arr[i]>secondLargest) {
34+
secondLargest = arr[i];
35+
}
36+
}
37+
}
38+
return secondLargest;
39+
}
40+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.coderolls.JavaPrograms.second_largest;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* A Java program to find the second largest number in an array
7+
* using Arrays.sort() method.
8+
*
9+
* @author coderolls.com
10+
*/
11+
public class SecondLargestElementInArrayUsingArrays {
12+
13+
public static void main(String[] args) {
14+
int[] arr = {2, 5, 9, 8, 11, 18, 13};
15+
16+
int secondLargest = getSecondLargest(arr);
17+
System.out.println("The second largest element in an array 'arr' is using Arrays.sort() :"+ secondLargest);
18+
}
19+
20+
private static int getSecondLargest(int[] arr) {
21+
Arrays.sort(arr);
22+
// return second largest, so length-2
23+
return arr[arr.length-2];
24+
}
25+
}

0 commit comments

Comments
 (0)