Java program to find second highest number in an integer Array

Java program to find second highest number in an integer Array

Write a java program to find second highest number in an integer array is one of the java coding interview questions asked many times to java fresher to check their ability to write code and their understanding of the language fundamentals. You may be asked to find the second largest number in the given array by iterating the array only once. In this post we will see two methods of solving the problem.

Java Program to find second highest number in an integer array without using sorting or collections

Below is the output of the above program.

Java Program to find second highest number in an integer array using sorting

Below is the output of the above program.
Note that the above program works well only when the input array does not contain duplicate elements.  For example in the above program if the input is new Integer[] { 46, 5, 64, 21, 64, 7, 3, 37, 12, 72,72,72 }) then output will be 72 instead of 64. Hence to handle duplicate elements the above program should be modified such that duplicates are removed from the array before using Arrays.sort() method. You can refer my another post to know how to remove duplicate elements from an array.

The above program can be written without using collections as below,

Below is the output of the above program.

Hope you find the post useful. If you think of any other logic, post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

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