Find Third largest element in an array
Input : arr[] = {1, 14, 2, 16, 10, 20}
Output : 14
Its a simple program, but would be great to know how it can be improved for better readability or any feedback regarding styling, etc.
public static int findThirdLargest(int[] numbers) {
if (numbers.length < 3) {
throw new IllegalArgumentException("there should be at least three numbers");
}
int largest, secondLargest, thirdLargest;
largest = secondLargest = thirdLargest = Integer.MIN_VALUE;
for (int number : numbers) {
if (number > largest) {
thirdLargest = secondLargest;
secondLargest = largest;
largest = number;
} else if (number > secondLargest) {
thirdLargest = secondLargest;
secondLargest = number;
} else if (number > thirdLargest) {
thirdLargest = number;
}
}
return thirdLargest;
}
@Test
public void findThirdLargest() throws Exception {
// with positive numbers
Assert.assertEquals(1, ThirdLargestNumber.findThirdLargest(new int[]{1, 2, 3}));
Assert.assertEquals(2, ThirdLargestNumber.findThirdLargest(new int[]{1, 2, 3, 4}));
Assert.assertEquals(2, ThirdLargestNumber.findThirdLargest(new int[]{1, 4, 3, 2}));
Assert.assertEquals(14, ThirdLargestNumber.findThirdLargest(new int[]{1, 14, 2, 16, 10, 20}));
Assert.assertEquals(16, ThirdLargestNumber.findThirdLargest(new int[]{19, -10, 20, 14, 2, 16, 10}));
// with negative numbers
Assert.assertEquals(-100, ThirdLargestNumber.findThirdLargest(new int[]{-100, -2, -3}));
Assert.assertEquals(-3, ThirdLargestNumber.findThirdLargest(new int[]{1, 2, -3, -1000}));
Assert.assertEquals(-3000, ThirdLargestNumber.findThirdLargest(new int[]{-1000, -2000, -3000, -4000, -5000}));
// what happens when all the numbers are same
Assert.assertEquals(1, ThirdLargestNumber.findThirdLargest(new int[]{1, 1, 1, 1}));
}