C Program to Find Second Largest Element in an Array

Here we’ll see the possible solutions of finding the second largest element in an array.

By Sorting the Array:

Easy solution that I can think of to find the second largest element in an array is to first sort the array and then pick the second or second last element of the array depending on whether the array is sorted in descending or ascending order.
In the following program we’ll first sort the array in ascending order using bubble sort. Once the array is sorted, then the second last element will be the second largest element.

Output of the Program:

Though this is very simple solution, it has some drawback. It time complexity is O(n2) whereas O(n) solution is possible. O(n2) is very inefficient compared to O(n).

Without Sorting

The following solution is by traversing the array once.

In every step of the two largest elements are kept. The variables are initialized with the first element of the array assuming that it will be the desired result. From next iteration, the current element of the array is compared with the highest element. If the current element is highest element, the previous highest element will replace the second highest element and will be replaced by the current element. If the current element of the array is not greater than the highest element but greater than the second highest element, then it will replace the second highest element. At the end of the iteration, the variable second_largest will be the second highest element.

Leave a Reply

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