Skip to content

SecondHighest

Find the second highest number from array without sorting and streams. Logic: keep two variables: first and second. Assign both variables Integer.MIN_VALUE Iterate over elements and check if current element is bigger that first.

Usage

    //        int[] arr = {0, 1, 2, 3, 1, 2};
    //        int[] arr = {5, 4, 3};
    int[] arr = { 2, 2, 1 };
    //        int[] arr = {3, 3, 3};
    //        int[] arr = {-1, -2, -3};
    //        int[] arr = {10, 8, 20, 3};
    int first = Integer.MIN_VALUE;
    int second = Integer.MIN_VALUE;
    for (int current : arr) {
        if (current > first) {
            second = first;
            first = current;
        } else if (current > second && current != first) {
            second = current;
        }
    }
    if (second == Integer.MIN_VALUE) {
        System.out.println("No second found");
    } else {
        System.out.println(second);
    }