Find second largest number in array in java

In this post, we will see how to find second highest number in array.


Problem

You need to find second highest number in array in O(n) time.

Solution

Here is the algorithm to solve this problem

  • Declare two variable highest and secondHighest with minimum value.
  • Iterate over array
  • When you find current element greater than highest then
    • secondHighest = highest
    • Highest = current element
  • If you find element greater than secondHighest
    • secondHigest = current element.

Here is Java code to find second largest number in array in java

When you run above program, you will get below output:

Second largest element in the array : 45

Leave a Reply

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