Java program to find second largest number in an array

Previous
Next

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

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

Problem :

Given an unsorted array, you need to find second largest element in the array in o(n) time complexity.
For example:

Solution:

You can sort the array and then return second last element in the array but it will be done in o(nlogn) time,

Algorithm:

  • Initialize highest and secondHighest with minimum possible value.
  • Iterate over array.
  • If current element is greater than highest
    • Assign secondHighest = highest
    • Assign highest = currentElement
  • Else if current element is greater than secondHighest
    • Assign secondHighest =current element.

Java Program to find second largest number in array:

Create a main java class named “FindSecondLargestMain.java”.

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

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog