find the index of second largest number in an array
Answers
Answered by
0
Find Second largest element in an array
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. Input : arr[] = {10, 5, 10} Output : The second largest element is 5. Input : arr[] = {10, 10, 10} Output : The second largest does not exist. Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.A simple solution will be first sort the array in descending order and then return the second element from the sorted array. The time complexity of this solution is O(nlogn).
A Better Solution is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n).
A more Efficient Solution can be to find the second largest element in a single traversal.
Below is the complete algorithm for doing this:
Similar questions