#include <stdio.h>
#include <limits.h>

int findSecondLargest(int arr[], int n) {
    if (n < 2) {
        return -1; // Not enough elements
    }

    int first = INT_MIN, second = INT_MIN;

    for (int i = 0; i < n; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] < first) {
            second = arr[i];
        }
    }

    return (second == INT_MIN) ? -1 : second; // Return -1 if second largest doesn't exist
}

int main() {
    int array[] = {12, 35, 1, 10, 34, 1};
    int n = sizeof(array) / sizeof(array[0]);
    int result = findSecondLargest(array, n);
    
    if (result != -1) {
        printf("The second largest element is: %d\n", result);
    } else {
        printf("There is no second largest element.\n");
    }

    return 0;
}

Explanation

  1. Include Headers: The program starts by including the standard input-output header (<stdio.h>) and the limits header (<limits.h>) for defining constants.
  2. Function Definition: The function findSecondLargest takes an array and its size as arguments. It returns the second largest element or -1 if it doesn’t exist.
  3. Edge Case Check: The function first checks if the size of the array is less than 2. If so, it returns -1, indicating there aren’t enough elements.
  4. Initialization: Two variables, first and second, are initialized to the smallest possible integer value (INT_MIN). This allows for comparison with any number in the array.
  5. Iteration: The function loops through the array:
    • If the current element is greater than first, it updates second to be first and sets first to the current element.
    • If the current element is not larger than first but is larger than second, it updates second.
  6. Return Value: After the loop, if second is still INT_MIN, it means there was no valid second largest element, and the function returns -1. Otherwise, it returns the value of second.

Output

For the input array {12, 35, 1, 10, 34, 1}, the output will be:

csharpCopy codeThe second largest element is: 34

This implementation efficiently finds the second largest element in a single pass through the array, achieving O(n) time complexity.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights