Java Interview Program to find second highest number in an integer array without sorting the elements.
- package com.instanceofjava;
- class SecondLargestNumber{
- public static void main(String args[])
- {
- int numbers[] = {6,3,37,12,46,5,64,21};
- int highest = 0;
- int second_highest = 0;
- for(int n:numbers){
- if(highest < n){
- second_highest = highest;
- highest =n;
- } else if(second_highest < n){
- second_highest = n;
- }
- }
- System.out.println("First Max Number: "+highest);
- System.out.println("Second Max Number: "+second_highest);
- }
- }
Output:
- First Max Number: 64
- Second Max Number: 46
Java Interview Program to find second highest number in an integer array by sorting the elements.
- package com.instanceofjava;
- class SecondLargestNumber{
- public static void main(String args[])
- {
- int numbers[] = {6,3,37,12,46,5,64,21};
- Arrays.sort(numbers);
- System.out.println("Largest Number: "+numbers[numbers.length-1]);
- System.out.println("Second Largest Number: "+numbers[numbers.length-2]);
- }
- }
Output:
- Largest Number: 64
- Second Largest Number: 46
import java.io.*;
ReplyDeleteclass Secondhigh
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.println("enter size");
n=Integer.parseInt(br.readLine());
System.out.println("enter array");
int[] a;
a=new int[n];
for(int i=0;ia[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
for(int i=0;i<n;i++)
System.out.print(a[i]);
System.out.println();
System.out.println(a[n-2]);
}
}
//add the pair of array and find highest and second_higest number;
ReplyDeletepackage com.ad;
public class ArrayAdd {
int hig,sec_hig, k, n,m=0;
void add() {
int a[]= {4,6,8,9,2,6};//add {4+6=10,6+8=14...2+6=8} i.e{10,14,17,11,8} and find highest,Second_hig number;
for(int i=0;i<a.length-1;i++) {
m++;
k=a[n]+a[m];
// System.out.println(k);
if(hig < k){
sec_hig = hig;
hig =k;
} else if(sec_hig < k){
sec_hig = k;
}
n++;
}
System.out.println("highest="+hig);
System.out.println("Second_hig="+sec_hig);
}
public static void main(String[] args){
ArrayAdd aa=new ArrayAdd();
aa.add();
}
}
int max =0;
ReplyDeleteint secmax = 0;
for(int i : arr) {
if(i > max) {
secmax = max;
max = i;
}
else if(i > secmax && i != max) {
secmax = i;
}
}
int[] res = {max, secmax};
return res;