Java Program to find Second Largest Number in an Array

Solution:

Before diving into the solution, let me tell you this the most common question which gets asked in the most coding rounds and if you are being lazy to practice and learn this now, you are fooling yourself.
Learn the logic behind this and you'll also realize after cracking the logic of this code you have learned a beautiful algorithm from DSA, but you have to figure out that yourself.

public class SecondLargestInArrayExample{
public static int getSecondLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
    {
        for (int j = i + 1; j < total; j++)
        {
            if (a[i] > a[j])
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
return a[total-2];
}

public static void main(String args[]){
    int a[]={1,2,5,6,3,2};
    int b[]={44,66,99,77,33,22,55};
    System.out.println("Second Largest: "+getSecondLargest(a,6));
    System.out.println("Second Largest: "+getSecondLargest(b,7));
    }
}

Output:
Second Largest: 5
Second Largest: 77

Comments

Popular posts from this blog

Priority Scheduling Algorithm Java Program.

Implement UNIX system calls like ps, fork, join, exec family, and wait for process management (use shell script/ Java/ C programming).

Implement a class CppArray which is identical to a one-dimensional C++ array (i.e., the index set is a set of consecutive integers starting at 0) except for the following : 1. It performs range checking. 2.It allows one to be assigned to another array through the use of assignment operator. 3.It supports a function that returns the size of the array.