Dipu Dipu - 11 months ago 31
Java Question

Find third largest no in Java

I'm little confused with this simple program.I have to find third largest no in array.I have done some code but getting only second largest no problem in third largest no so please suggest me what is wrong with this solution:

class ArrayExample {
public static void main(String[] args) {
int secondlargest = Integer.MIN_VALUE;
int thirdlargest = Integer.MIN_VALUE;
int largest = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
if (secondlargest < arr[i] && largest != arr[i]) {
thirdlargest = secondlargest;
secondlargest = arr[i];
if (thirdlargest < arr[i] && secondlargest != arr[i])
thirdlargest = arr[i];

System.out.println("Second Largest number is: " + secondlargest
+ "\nThird largest number is=====" + thirdlargest);


I would try something like this:

if (largest < ar[i]) {
    thirdlargest = secondlargest;
    secondlargest = largest;
    largest = arr[i];
} else if (secondlargest < ar[i]) {
    thirdlargest = secondlargest;
    secondlargest = ar[i];
} else if (thirdlargest < ar[i]) {
    thirdlargest = ar[i];

Not tested but I think the second IF isn't needed anymore.

Code Explanation:

We are verifying that if an entered number is greater than largest then move the third, second and 1st largest values one level up. If an entered value is greater than 2nd largest and less than largest, then move 3 and 2 one level up. If entered values is greated than 3rd largest and less than 2nd largest then move 3rd largest to the entered value.