Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The largest second number

Tags:

java

I searched everywhere for a solution to find the second largest number, but I got one solution in all sites, and it's wrong.

The code I found:

public static void main(String[] args) {
    int arr[] = { 1, 23, 47, 81, 92, 88, 52, 48, 56, 66, 65, 76, 71, 85,
                   49, 53, 56, 61, 65, 84 };
    secondLargeNumber(arr);
}

public static void secondLargeNumber(int[] arr) {
    int largest = arr[0];
    int secondLargest = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest) {
            secondLargest = arr[i];
        }
    }
    System.out.println("second largest in array is:" + secondLargest);

}

The code works fine , but if I changed the input sequence to:

 int arr[] = { 11, 10, 11, 2, 3, 4, 5, 6, 7, 8};

the output will be:

second largest in array is:11

I really don't know what to do!

like image 705
Duaa Isaa Avatar asked Sep 07 '13 13:09

Duaa Isaa


People also ask

What is the 2nd largest number?

Googol: A large number. A "1" followed by one hundred zeros. Googolplex: The second largest number with a name.

How do you find the second largest number in an array?

The simple approach to find second largest element in array can be running two loops. The first loop will find the first largest element in the array. After that, the second loop will find the largest element present in the array which is smaller than first_largest.


1 Answers

Just do:

else if (arr[i] > secondLargest && arr[i] != largest) {
    secondLargest = arr[i];
}
like image 135
Jean Logeart Avatar answered Sep 28 '22 03:09

Jean Logeart