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);
}
}
Sorting an arrayIf the first element is greater than the second swap them. Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them. Repeat this till the end of the array. After sorting an array print the third element from the end of the array.
Solution Approach For the largest three elements, we will create three elements holding their values, max, max2 and max3 and set these values to arr[0]. if (arr[i] > max) -> max3 = max2, max2 = max , max = arr[i]. else if (arr[i] > max2) -> max3 = max2, max2 = arr[i].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With