Java Program to Find Second Largest Number in an Array

Write a java program to find second largest number in an array. Given an unsorted array, write a java code to find second highest number in an array.

For solving this type of problems time complexity is an important factor. Try to solve this problem in a minimum time complexity. In this tutorial, We are going to discuss multiple approaches and their time complexities.

For example – Let’s take an array.

Input – arr[] = { 1, 9, 5, 2, 8, -1, 3, 55}

Output: 9

The second largest number in this array is 9.

Before solving this problem think for a moment how do you solve this problem. Which approach you prefer and why?


The easiest approach is to sort the array.  After sorting the number present at n-2 index is the second largest number in an array.

Bubble Sort Program in Java

Insertion Sort Program in Java

For sorting either we can write our own sort method using Sorting algorithms or we can use java inbuilt sort method. The time complexity of sorting an array is O(nlogn).

NOTE: If the element of an array is repeated then this approach won’t work.

To understand this let’s take an example.

int num[] = {1, 9, 5, 55, 8, -1, 3, 55};

So what will be the second highest number if we use above method (sort and pick the element at n-2). The element is 55 which is wrong.

The best approach is to traverse an array to find second highest number. Let’s implement this approach.

Subscribe Our Tutorials

Get Latest Updates on Facebook

Java Program to Find the Second Highest Number in an Array

Java Program to Find Second Largest Number in an Array

Java Program to Find Second Largest Number in an Array without Sorting

In this approach, we traverse an array and maintain two indexes highest and secondHighest. The time complexity of this approach is O(n).


Find Second Highest Number in an Array : Video Tutorial

In this video tutorial, I have explained how we can find second largest number without sorting an array.

Java program to find the first non-repeated character in a string

Find pair of elements in an array whose sum is equal to a given number

I have discussed two approaches to solve this problem. If you know some other better way to solve this problem then you can discuss with us through your comments.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.