Program to print second largest number in an array without sorting

2ndlr

 
public class SecLargest {

public static void main(String[] args) {
// TODO Auto-generated method stub

int[] num = {15000,9,80,7,8000,0,12000,3,5,2500,4000,5099};
int k = num[0];

// loop for largest number
for(int i=0;i<num.length;i++)
{
if(num[i]>k)
{
k=num[i];
}
}

int t;
if(k!=num[0]) // if k is not first element of array
{
t = num[0];
}
else // if k first element of array
{
t = num[1];
}

// loop for 2nd largest number
for(int i=0;i<num.length;i++)
{
if(num[i]>t && num[i]!=k)
{
t = num[i];
}
}

//System.out.println(k); // largest number
System.out.println(t); // 2nd largest number

}

}

You may also like...

1 Response

  1. Rishi says:

    Awesome one……removed the hidden bug for the first element…..Great Job!!!

Leave a Reply to Rishi Cancel reply

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