Hi ,
Please find below the code to find second highest number in an array in java.
Method 1:
public class SecondHighestNumber {
public static void main(String[] args) {
int [] arr = { 1,19,9,7,5,2,3,4,16,12};
int firstHighest , secondHighest , i;
if(arr[0] > arr[1])
{
firstHighest = arr[0];
secondHighest = arr[1];
}
else
{
firstHighest = arr[1];
secondHighest = arr[0];
}
for(i=2;i<arr.length();i++)
{
if(arr[i] >= firstHighest)
{
secondHighest = firstHighest;
firstHighest = arr[i];
}
else if(arr[i]>secondHighest)
{
secondHighest = arr[i];
}
}
System.out.println(" The Second highest number in an array is "+secondHighest);
}
}
Please find below the code to find second highest number in an array in java.
Method 1:
public class SecondHighestNumber {
public static void main(String[] args) {
int [] arr = { 1,19,9,7,5,2,3,4,16,12};
int firstHighest , secondHighest , i;
if(arr[0] > arr[1])
{
firstHighest = arr[0];
secondHighest = arr[1];
}
else
{
firstHighest = arr[1];
secondHighest = arr[0];
}
for(i=2;i<arr.length();i++)
{
if(arr[i] >= firstHighest)
{
secondHighest = firstHighest;
firstHighest = arr[i];
}
else if(arr[i]>secondHighest)
{
secondHighest = arr[i];
}
}
System.out.println(" The Second highest number in an array is "+secondHighest);
}
}
No comments:
Post a Comment