Find Second Largest Number in Array – Infosys -CTS -TCS JAVA Interview Question
public class SecondLargestInArrayExample{
public static int getSecondLargest(int[] a, int total,int k){
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-k];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2,7}; /// 1,2,2,3,5,6,7 7-2 =5 0,1,2,3,4,
//int b[]={44,66,99,77,33,22,55};
int n=a.length;
int k=3;
System.out.println("Second Largest: "+getSecondLargest(a,n,k));
//System.out.println("Second Largest: "+getSecondLargest(b,7));
}
}
Post Views: 504