Skip to content

Create 011_Second_Largest_Element #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions 002_ARRAY/011_Second_Largest_Element
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// C++ program to find the second largest element in the array
#include <iostream>
using namespace std;


int secondLargest(int arr[], int n) {
int largest = 0, secondLargest = -1;

for (int i = 1; i < n; i++) {
if (arr[i] > arr[largest])
largest = i;
}

for (int i = 0; i < n; i++) {
if (arr[i] != arr[largest]) {

if (secondLargest == -1)
secondLargest = i;
else if (arr[i] > arr[secondLargest])
secondLargest = i;
}
}
return secondLargest;
}


int main() {
int arr[] = {10, 12, 20, 4};
int n = sizeof(arr)/sizeof(arr[0]);
int second_Largest = secondLargest(arr, n);
if (second_Largest == -1)
cout << "Second largest didn't exit\n";
else
cout << "Second largest : " << arr[second_Largest];
}