Find the Second Largest Element in a 1-D Array Without Sorting in C

This program finds the second largest element in a 1-D array in a single pass, without sorting the array.

C Program

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

int main() {
    int arr[100], n, i;
    int largest = INT_MIN, second = INT_MIN;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

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

    if (second == INT_MIN) {
        printf("There is no second largest element (all elements may be equal).\n");
    } else {
        printf("Largest element: %d\n", largest);
        printf("Second largest element: %d\n", second);
    }

    return 0;
}

Explanation

  • largest and second both start at INT_MIN so any real array value will be greater on the first comparison.
  • While scanning, whenever a new element beats largest, the old largest is demoted to second before updating largest.
  • Otherwise, if the element is between second and largest (and not equal to largest, to avoid counting a duplicate maximum as the second largest), it becomes the new second.
  • This does the job in one pass (O(n)) instead of sorting the whole array first.

Sample Output

Enter number of elements: 6
Enter 6 elements:
10 25 8 25 17 3
Largest element: 25
Second largest element: 17

Leave a Comment