File size: 584 Bytes
c574d3a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class LargestSecondElementInArray {
static int LargestElement(int arr[]){
int largest = 0;
for(int i=0;i<arr.length-1;i++)
{
if(arr[i]>arr[largest])
{
largest = i;
}
}
return largest;
}
static int SecondLargest(int arr[]) {
int largest = LargestElement(arr);
int res = -1;
for(int i = 0;i<arr.length-1;i++)
{
if(arr[i]!=arr[largest])
{
if(res==-1)
res=1;
else if(arr[i]>arr[res])
res = i;
}
}
return arr[res];
}
public static void main(String[] args) {
int arr[] = {5,10,8,20};
System.out.println(SecondLargest(arr));
}
}
|