Advertisement
YouKnowWho07

Find 2nd largest element array

Jun 21st, 2023 (edited)
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.57 KB | None | 0 0
  1. /// Find 2nd largest element array
  2.  
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. int findSecondLargest(int a[], int n)
  7. {
  8.    sort(a, a + n);  
  9.  
  10.    int second_largest = 0;
  11.    for (int i = n - 2; i >= 0; i--)
  12.    {
  13.       if (a[i] != a[n - 1])
  14.       {
  15.          second_largest = a[i];
  16.          break;
  17.       }
  18.    }
  19.    return second_largest;
  20. }
  21.  
  22. int main()
  23. {
  24.    int a[] = {12, 35, 1, 10, 34, 1};
  25.   int n = sizeof(a) / sizeof(a[0]);
  26.    
  27.    int answer = findSecondLargest(a, n);
  28.    cout << "The second largest element in the array is: " << answer;
  29.  
  30.    return 0;
  31. }
  32.  
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement