Write a Java program to find the second highest number in an integer array.

public class SecondHighestNumber {
    public static int findSecondHighest(int[] arr) {
        int max1 = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;
        for (int i : arr) {
            if (i > max1) {
                max2 = max1;
                max1 = i;
            } else if (i > max2 && i < max1) {
                max2 = i;
            }
        }
        return max2;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        System.out.println("Second highest number is: " + findSecondHighest(arr));
    }
}
Second highest number is: 8

This program uses a simple iterative approach to traverse through the array, maintaining two variables max1 and max2. It compares each element of the array with max1 and max2. If the current element is greater than max1, it becomes the new max1 and max2 becomes the old max1. If the current element is less than max1 but greater than max2, it becomes the new max2. This way, at the end of the loop, max1 will contain the highest number and max2 will contain the second highest number.

This program has a Time Complexity of O(n) as it iterates through the array once.

Please note that this program assumes that the array has at least two distinct elements, if it is not the case it will throw an exception.

Leave a Reply

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