Interview Question: Find Second Largest Number

preview_player
Показать описание
I try my best
Visit my website:
Рекомендации по теме
Комментарии
Автор

And if we have array constructed like {4, 55, 43, 52, 55}; (generally speaking multiple max value) Your algorithm will fail. (because of that else if to be specific) . 

else if(secondbiggest<tab[i] && tab[i]!=biggest)

adding that AND will solve issue. 

Nemeczekes
Автор

/* works like a pro, thanks :) source code buddies ..*/
public class SecHighest {

public static void main(String[] args) {

System.out.println(" Numbers :");
int arr[]= {10, 34, 53, 93};

int fh =arr[0], sh=arr[0] ;

for(int i=0;i<arr.length;i++){

if(arr[i]>fh){

sh=fh;
fh=arr[i];
}
else if ( sh<arr[i]){

sh=arr[i];
}

}

System.out.println("Secound highest number is :"+sh);
}
}

Anilkumar-ecsj
Автор

package BufferIo;

public class ArrayExample {

public static void main(String args[]){
int ar[]={1, 2, 3, 4, 5, 6, 7};
int thirdlargest=ar[0], secondlargest=ar[0], largest=ar[0];

for(int i=0;i<ar.length;i++){
if (largest < ar[i]) {
thirdlargest = secondlargest;
secondlargest = largest;
largest = ar[i];
} else if (secondlargest < ar[i]) {
thirdlargest = secondlargest;
secondlargest = ar[i];
} else if (thirdlargest < ar[i]) {
thirdlargest = ar[i];
}

}

System.out.println(largest);




}}

Anilkumar-ecsj