Skip to content

Commit 8939dae

Browse files
committed
feat: add implementation for finding the second largest element
1 parent ef6084a commit 8939dae

3 files changed

Lines changed: 46 additions & 0 deletions

File tree

VUPC/March/first.cpp

Whitespace-only changes.

VUPC/SecondLargest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
public class SecondLargest{
2+
public static void main(String[] args) {
3+
int [] array = {1,2,3,8,5,6,7,8};
4+
int max = Integer.MIN_VALUE;
5+
int secondMax = Integer.MIN_VALUE;
6+
7+
for (int element: array){
8+
if (element > max){
9+
secondMax = max;
10+
max = element;
11+
} else if (element > secondMax && element < max){
12+
secondMax = element;
13+
}
14+
}
15+
16+
System.out.println(secondMax);
17+
}
18+
}

VUPC/secondLargest.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <climits>
2+
#include <iostream>
3+
using namespace std;
4+
5+
int secondLargest(int array[], int size) {
6+
int max = INT_MIN;
7+
int secondMax = max;
8+
9+
for (int i = 0; i < size; i++) {
10+
if (array[i] > max) {
11+
secondMax = max;
12+
max = array[i];
13+
} else if (array[i] > secondMax && array[i] < max) {
14+
secondMax = array[i];
15+
}
16+
}
17+
18+
return secondMax;
19+
20+
return 0;
21+
}
22+
23+
int main() {
24+
int array[] = {1, 2, 3, 8, 4, 5, 6, 7, 8, 8};
25+
int size = sizeof(array) / sizeof(array[0]);
26+
27+
cout << secondLargest(array, size) << endl;
28+
}

0 commit comments

Comments
 (0)