Find Second largest element in an array using C Programming

C ProgrammingPlacements Questions

Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.

Example:

Input: arr[] = {12, 35, 1, 10, 34, 1}
Output: The second largest element is 34.
Explanation: The largest element of the
array is 35 and the second
largest element is 34

Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of
the array is 10 and the second
largest element is 5

Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array
is 10 there is no second largest element

Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array

// C program to find second largest element in an array
#include <stdio.h>
#include <stdlib.h>
 
// Compare function for qsort

int cmpfunc(const void* a, const void* b)
{

    return (*(int*)a - *(int*)b);
}
 
/* Function to print the second largest elements */

void print2largest(int arr[], int arr_size)
{

    int i, first, second;

    /* There should be atleast two elements */

    if (arr_size < 2) { 
         printf(" Invalid Input "); 
          return;
    }

    // sort the array 
    qsort(arr, arr_size, sizeof(int), cmpfunc); 
    // start from second last element as the largest element 
    // is at last 
    for (i = arr_size - 2; i >= 0; i--) {

        // if the element is not

        // equal to largest element

        if (arr[i] != arr[arr_size - 1]) {

            printf("The second largest element is %d\n",arr[i]);

            return;

        }

    }

    printf("There is no second largest element\n");
}
 
/* Driver program to test above function */

int main()
{

    int arr[] = { 12, 35, 1, 10, 34, 1 };

    int n = sizeof(arr) / sizeof(arr[0]);

    print2largest(arr, n);

    return 0;
}
 

Output : 

The second largest element is 34

Complexity Analysis:

Time Complexity: O(n log n).
Time required to sort the array is O(n log n).

Auxiliary space: O(1).
As no extra space is required.

     

Advertisements

ads